如何使用 JavaScript [Typescript ES5] 在 JSON 中编辑密码
How to redact password in JSON using JavaScript [Typescript ES5]
我有一个看起来像这样的对象:
{
"property1": "value1",
"headers": {
"property2": "value2",
"Authentication": "Basic username:password"
},
"property3": "value3"
}
我需要编辑密码并保留用户名。
来自 Delete line starting with a word in Javascript using regex 我试过:
var redacted = JSON.stringify(myObj,null,2).replace( /"Authentication".*\n?/m, '"Authentication": "Basic credentials redacted",' )
... 但这不会保留用户名并在所有双引号前插入反斜杠 ( "
--> \"
).
什么是正确的正则表达式来反应密码文字字符串并保持其他一切不变?
使用替换参数。
RTM:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
示例:
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)
如果我没听错,假设 Authentication
只包含一个 :
,
这可能是这样的:
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));
我有一个看起来像这样的对象:
{
"property1": "value1",
"headers": {
"property2": "value2",
"Authentication": "Basic username:password"
},
"property3": "value3"
}
我需要编辑密码并保留用户名。
来自 Delete line starting with a word in Javascript using regex 我试过:
var redacted = JSON.stringify(myObj,null,2).replace( /"Authentication".*\n?/m, '"Authentication": "Basic credentials redacted",' )
... 但这不会保留用户名并在所有双引号前插入反斜杠 ( "
--> \"
).
什么是正确的正则表达式来反应密码文字字符串并保持其他一切不变?
使用替换参数。
RTM:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
示例:
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)
如果我没听错,假设 Authentication
只包含一个 :
,
这可能是这样的:
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));