在 JSON 字符串中,给定键的所有字符串值如何替换特定子字符串的任何出现?

Within a JSON string how does one for all string values of a given key replace any occurrence of a specific substring?

我正在寻找一种方法来用另一个字符串替换 JSON 中的给定字符串,但仅限于某个键。例如,假设我有以下 JSON、data:

[
    {
        "name": "please, I said please",
        "title": "Test One",
        "more": [
            {
                "name": "another name",
                "title": "please write something"
            }
        ]
    },
    {
        "name": "testTwo",
        "title": "Test Two"
    },
    {
        "name": "testThree",
        "title": "Test Three"
    },
    {
        "name": "testFour",
        "title": "Test Four"
    }
]

举个例子,我想用“could you”替换所有出现的单词“please”。在这个例子中,我只想替换整个单词。现在,我有一个可以执行此操作的工作示例:

const wordToReplace = "please"

const jsonString = JSON.stringify(data)
const reg = new RegExp(`\b${wordToReplace}\b`, 'gi) // whole words only and case insensitive
const dataReplaced = jsonString.replace(reg, function () {
  return 'could you'
}

console.log(JSON.parse(dataReplaced))

给定上述代码,单词 'please' 将被所有出现的 'could you' 替换。但是,我只想在键是“标题”的情况下替换这些词。现在,它将为任何给定的密钥替换它(例如,在密钥为 'name' 和 'title' 的第一个实例中)。

还有一点需要注意,JSON 可以有不同数量的嵌套属性,正如您从示例中看到的那样。它并不总是嵌套在 objects 中。

此外,我在 replace 方法中添加函数的原因是因为我正在尝试指定键的方法。

我不建议在 json 转换为字符串时使用 replace

相反,我会递归循环遍历 array/objects 并根据需要更改值

简单示例:

const data = [{"name": "please, I said please", "title": "Test One", "more": [{"name": "another name", "title": "please write something"} ] }, {"name": "testTwo", "title": "Test Two"}, {"name": "testThree", "title": "Test Three"}, {"name": "testFour", "title": "Test Four"} ];
const regx = new RegExp(`\bplease\b`, 'gi');

function replace(obj) {
    for (var k in obj) {
        if (typeof obj[k] == "object" && obj[k] !== null) {
            replace(obj[k]);
        } else if (k === 'title') {
            obj[k] = obj[k].replaceAll(regx, 'could you');
        }
    }
    return obj;
}

const result = data.map(o => replace(o));
console.log(result);

无需重新发明轮子。两者 JSON methods, JSON.parse and JSON.stringify 都能够处理额外提供的回调 ...

const sampleJSON = '[{"name":"please, I said please","title":"Test One","more":[{"name":"another name","title":"please write something"}]},{"name":"testTwo","title":"Test Two"},{"name":"testThree","title":"Test Three"},{"name":"testFour","title":"Test Four"}]'

const sampleData = JSON.parse(sampleJSON, (key, value) => {
  const regX = (/\bplease\b/gmi);

  return (key === 'title' && regX.test(value))
    ? value.replace(regX, 'could you')
    : value;
});

console.log({ sampleData });
console.log('JSON.parse(sampleJSON) ...', JSON.parse(sampleJSON));
.as-console-wrapper { min-height: 100%!important; top: 0; }

const sampleData = [{
  name: 'please, I said please',
  title: 'Test One',
  more: [{
    name: 'another name',
    title: 'please write something',
  }],
}, {
  name: 'testTwo',
  title: 'Test Two',
}, {
  name: 'testThree',
  title: 'Test Three',
}, {
  name: 'testFour',
  title: 'Test Four',
}];

const sampleJSON = JSON.stringify(sampleData, (key, value) => {
  const regX = (/\bplease\b/gmi);

  return (key === 'title' && regX.test(value))
    ? value.replace(regX, 'could you')
    : value;
});

console.log({ sampleJSON });
console.log("JSON.stringify(sampleData) ...", { stringifed: JSON.stringify(sampleData)});
.as-console-wrapper { min-height: 100%!important; top: 0; }