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?
CodePudding user response:
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)
CodePudding user response:
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));