I am building a JSON file dynamically. I want to add a JSON array in the JSON object. The JSON looks like-
{"name":"Root",
"children":[
{"name":"child1"},
{"name":"child2"}
]}
Now, I want to add -
[{"name":"child11"},{"name":"child12"}]
under "child1" object. How to do it? I have also tried keeping blank children object while creating the original JSON object, but JSON parser doesn't keep those empty children block. In current scenario, when I am using push() function to add new child it throws exception. Any help is much appreciated. Thanks in advance!!
Edit1: I think I didn't made myself clear enough. I have researched SO before posting this question, and I guess this is not a duplicate question. My target JSON is -
{
"name": "Root",
"children": [{
"name": "child1",
"children": [{
{"name": "child11"},
{"name": "child12"}
}]
},
{
"name": "child2",
"children": [{
{"name": "child21"},
{"name": "child22"}
}]
}
]
};
Here is the code snippet that I am trying to run -
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();
}
}
}