I’m fairly new to using JSON (as opposed to XML) and am currently working purely with Javascript to digest, parse and display my returned JSON data.
I’m using the JSON2.js library and am getting back some valid JSON data representing a fairly simple nested list:
{
"node":{
"class":"folder",
"title":"Test Framework",
"node":{
"class":"folder",
"title":"Item 1",
"node":{
"class":"folder",
"title":"Item 1.1",
"node":{
"class":"file",
"title":"Item 1.1.a"
}
},
"node":{
"class":"folder",
"title":"Item 1.2",
"node":{
"class":"file",
"title":"Item 1.2.a"
},
"node":{
"class":"file",
"title":"Item 1.2.b"
},
"node":{
"class":"file",
"title":"Item 1.2.c"
}
},
"node":{
"class":"folder",
"title":"Item 1.3",
"node":{
"class":"folder",
"title":"Item 1.3.a",
"node":{
"class":"file",
"title":"Item 1.3.a.i"
},
"node":{
"class":"file",
"title":"Item 1.3.a.ii"
}
}
}
},
"node":{
"class":"folder",
"title":"Item 2",
"node":{
"class":"file",
"title":"item 2.a"
},
"node":{
"class":"file",
"title":"Item 2.b"
}
}
}
}
Does anyone have any pointers for a quick way to turn that lot into a UL with all of the nested elements? It would be cool as well if the “class” element that’s in the JSON could be used as the class for each LI.
Any help is much appreciated.
Thanks,
Dave.
Your json is unsuited to your task. Some objects have several properties with the same name (“node”), so they are overriding one another. You have to use arrays of nodes instead. Here is a working data structure and the functions that can turn it into a nested list:
And I can add this css to have the items numberings match the node titles 🙂
See it in action.