簡體   English   中英

在 JSON 字符串中,給定鍵的所有字符串值如何替換特定 substring 的任何出現?

[英]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"
    }
]

例如,我希望將所有出現的“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方法中添加了 function 的原因是因為我沒有嘗試指定密鑰的方法。

無需重新發明輪子。 JSON方法, JSON.parseJSON.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; }

我不建議在轉換為字符串的 json 上使用replace

相反,我會遞歸循環遍歷數組/對象並在需要時更改值

簡單的例子:

 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM