I'm looking for a way to replace a given string in a JSON by another string, but only for a certain key. For example, suppose I have the following 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"
}
]
Let's say for example, I am looking to replace all occurrences of the word "please" by "could you". In this example, I only want to replace whole words. Right now, I've got a working example which does this:
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))
Given the above code, the word 'please' will be replaced by 'could you' for all occurrences. However, I want to replace the words only if the key is "title". Right now, it will replace it for any given key (for example, in the first instance where the key is 'name' and also 'title').
One more thing to note is that the JSON can have a varying amount of nested properties as you can see from the example. It's not always the same nested objects within.
Also, the reason I've added a function in the replace
method is because I wast trying out ways to specify a key.