1

I have an object that looks like this:

{
  "property1": "value1",
  "headers": {
    "property2": "value2",
    "Authentication": "Basic username:password"
  },
  "property3": "value3"
}

I need to redact password and preserve username.

From Delete line starting with a word in Javascript using regex I tried:

var redacted = JSON.stringify(myObj,null,2).replace( /"Authentication".*\n?/m, '"Authentication": "Basic credentials redacted",' )

... but this doesn't preserve the username and inserts a backslash in front of all double quotes ( " --> \").

What is the correct regex expression to react the password literal string and leave everything else intact?

aenagy
  • 37
  • 6

2 Answers2

2

Use the replacer argument.

RTM: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Example:

const obj = {
  "property1": "value1",
  "headers": {
    "property2": "value2",
    "Authentication": "Basic username:password"
  },
  "property3": "value3"
};

const redacted = JSON.stringify(obj, (k, v) => k === 'Authentication' ? v.split(':')[0]+':<redacted>' : v, 2)

console.log(redacted)
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
2

If I got you correctly, assuming the Authentication contains only one :, this may be the way:

const replacePassword = ({ headers, ...obj }, newPassword)=> {
        const { Authentication } = headers;
        return {
            ...obj,
            headers: {
                ...headers,
                Authentication: Authentication.replace(/(?<=:).*$/, newPassword)
            }
        };
    };
    
const obj = {
    "property1": "value1",
    "headers": {
        "property2": "value2",
        "Authentication": "Basic username:password"
    },
    "property3": "value3"
};

console.log(JSON.stringify(replacePassword(obj, 'my-new-password'), null, 3));
chenkop1
  • 21
  • 1