Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  56] [ 7]  / answers: 1 / hits: 36680  / 12 Years ago, fri, march 2, 2012, 12:00:00

I want to create a multi-level JSON string with JS.



Scenario



3 countries with 5 grandfathers with 3 kids which whom also have 3 kids that have 5 friends.



I get the data from a external JSON file that looks like this.



 {countries:[
{
name:USA,

grandfathers:[
{
gFName:Steve,
grandfathersKid:[
{
gFKName: Linda,
kid: [{
name: Steve JR,
friends: [{
name: Kriss|John|Martin|Steven
}]
}
]
}

]
}
]
}
]}


And now I want to store some of the countries with people and their relatives and friends in a a new JSON list that looks exactly as the list made in the external json file. I aim to use this homemade list later on in the script.



My initial response for this was



var tree = new Array();

tree = {};


var countries = new Array();

countries[0] = canada;
countries[1] = USA;
countries[2] = Mexico;
countries[0][0] = Steve; //Lives in Canada
countries[0][0][0] = Linda; //Daughter of Steve
countries[0][0][0][0] = Steve JR; // Kid of Linda
countries[0][0][0][0][0] = Kriss; //Steves Friend
...


$.each(countries...function(index, value){
tree[index].country = value;

$.each(grandfathers...function(key, value){
tree[index].country[key].grandfather = value;

}


And so on, but this is not giving me the result I want. What am I doing wrong? And a more effective way than to take each of everything?



Third edit...


More From » json

 Answers
11

Is this the sort of thing you're trying to do?



var countries = $.map(oldCountries || [], function(country) {
return {
name: country.name,
people: $.map(country.grandfathers || [], function(gpa) {
return {
name: gpa.gFName,
children: $.map(gpa.grandfathersKid || [], function(parent) {
return {
name: parent.gFKName,
children: $.map(parent.kid || [], function(kid) {
return {
name: kid.name,
friends: kid.friends
};
})
};
})
};
})
};
});


I wasn't sure what to do with the friends node. Should that be normalized into something more useful, or do you want to leave it alone?



This Fiddle demonstrates the technique.


[#87085] Thursday, March 1, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
frederickmohamedw questions
Wed, Sep 23, 20, 00:00, 4 Years ago
Sat, Jul 18, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Jan 11, 20, 00:00, 4 Years ago
Fri, Dec 27, 19, 00:00, 4 Years ago
;