替换JSON中的嵌套字符串 [英] Replace nested string in JSON
本文介绍了替换JSON中的嵌套字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试做两件事:
- 在JSON文件中搜索字符串("TODO")
- 替换 带有先前发生的字符串的字符串(开始测验")
- Search a JSON file for a string ("TODO")
- Replace that string with the string that occurred previously ("Start Quiz")
因此,所有TODO必须替换为"englishDefault"中出现的字符串.
So, all the TODO's have to be replaced by the string occurring in "englishDefault".
我有以下JSON:
{
"semantics": [
{
"englishLabel": "Quiz introduction",
"fields": [
{
"englishLabel": "Display introduction",
},
{
"englishDefault": "Start Quiz",
"default": "TODO"
}
]
}
]
}
第2部分已经解决,但是我很难扩展答案: 替换为JSON数组中的前一个字符串
Part 2 has been solved already, but I am having trouble extending the answer: Replace with previous string in a JSON array
推荐答案
此处需要一系列for循环,根据您的示例,尚不清楚TODO是否可以出现在JSON结构中的任何地方或字段的下方,所以我将假设最简单,即它只能出现在fields数组中
You need a series of for loops here, from your example, it is not quite clear if TODO can appear anywhere in the JSON structures or just under the fields, so I will assume the simplest i.e. that it can only appear in the fields array
for(var i = 0; i < semantics[0].fields.length; i++)
{
var fields = semantics[0].fields[i];
//declare empty previous variable to store the previous key
var previousKey;
for (var key in fields) {
if (p.hasOwnProperty(key)) {
var value = fields[key];
if(value == 'TODO')
{
console.log('Found TODO, please replace');
}
else {
//If value was not TODO, then we save the present key to be used in the next iteration step as the previous key
previousKey = key;
}
}
}
}
这篇关于替换JSON中的嵌套字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文