【问题标题】:How to redact password in JSON using JavaScript [Typescript ES5]如何使用 JavaScript [Typescript ES5] 在 JSON 中编辑密码
【发布时间】:2021-11-19 17:38:37
【问题描述】:

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

{
  "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",' )

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

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

【问题讨论】:

    标签: javascript regex typescript redaction


    【解决方案1】:

    使用替换参数。

    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)

    【讨论】:

      【解决方案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));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-10
        • 1970-01-01
        • 2019-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-30
        相关资源
        最近更新 更多