我正在尋找一種方法將 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"
}
]
例如,我希望將所有出現的“please”一詞替換為“could you”。在這個例子中,我只想替換整個單詞。現在,我有一個作業示例可以做到這一點:
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”。但是,只有當鍵是“標題”時,我才想替換單詞。現在,它將為任何給定的鍵替換它(例如,在鍵是“名稱”和“標題”的第一個實體中)。
還有一點需要注意的是,從示例中可以看出,JSON 可以具有不同數量的嵌套屬性。它并不總是相同的嵌套物件。
另外,我在方法中添加函式的原因replace是因為我在嘗試指定鍵的方法。
uj5u.com熱心網友回復:
我不建議replace在轉換為字串的 json 上使用。
相反,我會遞回回圈遍歷陣列/物件并在需要時更改值
簡單的例子:
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416680.html
標籤:
