【发布时间】:2018-01-30 18:09:38
【问题描述】:
我正在动态构建一个 JSON 文件。我想在 JSON 对象中添加一个 JSON 数组。 JSON 看起来像-
{"name":"Root",
"children":[
{"name":"child1"},
{"name":"child2"}
]}
现在,我想添加 -
[{"name":"child11"},{"name":"child12"}]
在“child1”对象下。怎么做?我还尝试在创建原始 JSON 对象时保留空白子对象,但 JSON 解析器不会保留那些空子对象。在当前情况下,当我使用 push() 函数添加新子时,它会引发异常。任何帮助深表感谢。 提前致谢!!
Edit1:我觉得我说得不够清楚。在发布这个问题之前我已经研究过,我想这不是一个重复的问题。我的目标 JSON 是 -
{
"name": "Root",
"children": [{
"name": "child1",
"children": [{
{"name": "child11"},
{"name": "child12"}
}]
},
{
"name": "child2",
"children": [{
{"name": "child21"},
{"name": "child22"}
}]
}
]
};
这是我尝试运行的代码 sn-p -
flare = {
"name": "Root",
"children": [{
"name": "child1",
"children": [{
{"name": "child11"},
{"name": "child12"}
}]
},
{
"name": "child2",
"children": [{
{"name": "child21"},
{"name": "child22"}
}]
}
]
};
var updatedJson = twoLevelSelection(flare);
function twoLevelSelection(json){
var root = flare.name;
var string_json = '';
string_json = '{"name": "'+root+'","children": [';
flare.children.forEach(
function(d){
string_json = string_json+ '{"name":"'+d.name+'","children":[]},';
}
);
string_json = string_json.substring(0,string_json.length-1);
string_json = string_json + ']}';
return JSON.parse(string_json);
}
// data is the original data.i.e - flare
// d is the clicked node, under which children to be added
function traverse(data,d){
var queue = [];
var next = data;
while(next){
if(next.children){
next.children.forEach(
function(k){
queue.push(k);
}
)
}
if(queue[0].name==d.name){
alert(queue[0].children);
//d.children = queue[0].children;
var child_string='';
var child_array = [];
queue[0].children.forEach(
function(j){
child_string = '{"name": "'+j.name+'"}';
child_array.push(child_string);
}
);
console.log(child_array);
d.children = [...child_array];
console.log(updatedJson);
//update(updatedJson);
break;
}else{
next= queue.shift();
}
}
}
【问题讨论】:
-
新帐户 - 同样的问题
-
JSON, 是一个字符串。
-
@messerbill 也应该发布链接
-
欢迎来到 SO。请访问help center 了解内容和How to Ask。提示:发布工作和代码
-
问题已经结束,我再也找不到了 - 这是几天前的事
标签: javascript jquery json