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?
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)