1

我有一个看起来像这样的对象:

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

我需要编辑密码并保留用户名。

使用正则表达式的 Javascript 中以单词开头的删除行中,我尝试了:

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

...但这不会保留用户名并在所有双引号("--> \")前插入反斜杠。

什么是正确的正则表达式来反应密码文字字符串并保持其他所有内容不变?

4

2 回答 2

2

使用替换参数。

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)

于 2021-09-27T15:07:02.523 回答
2

如果我没听错的话,假设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));

于 2021-09-27T15:21:24.787 回答