About an hour ago I made a post (that I have deleted) about getting contents of a JSON file. It struck me only later that JSON is simply accessible as a JS Object, so accessing the object isn't an issue any longer. However, now I want to recursively add elements to an HTML list and I am making a logical flow error somewhere, but I just can't figure out how to solve it. (I've been working five hours straight, so that might be a cause).
function init(src) {
$.getJSON(src, {
format: "json"
}).done(function (data) {
var json = $(data);
main(json);
});
}
function main(json) {
var base = $("body");
base.html(traverse(json[0]));
}
function traverse(node) {
var newList = $("<ol/>");
if (typeof node == "object") {
$.each(node, function (k, v) {
var newItem = $('<li><a href="#">' + k + '</a></li>');
traverse(v);
newItem.appendTo(newList);
});
} else {
// Not sure if `$(this)` will simply return this item's name?
var newItem = $('<li><a href="#">' + $(this) + '</a></li>');
newItem.appendTo(newList);
}
return newList;
}
init("myjson.json");
Example input of myjson.json
:
{
"S": {
"NP": {
"N": "i"
},
"VP": {
"V": "like",
"NP": {
"Det": "the",
"N": "bananas"
}
}
}
}
The recursion stops after a single item is added, so the output is:
<ol><li>S</li></ol>
But the expected output is:
<ol>
<li>S
<ol>
<li>NP
<ol>
<li>N
<ol>
<li>i</li>
</ol>
</li>
</ol>
</li>
<li>VP
<ol>
<li>V
<ol>
<li>like</li>
</ol>
</li>
<li>NP
<ol>
<li>Det
<ol>
<li>the</li>
</ol>
</li>
<li>N
<ol>
<li>bananas</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>