I'd like to traverse a JSON object tree, but cannot find any library for that. It doesn't seem difficult but it feels like reinventing the wheel.
In XML there are so many tutorials showing how to traverse an XML tree with DOM :(
I'd like to traverse a JSON object tree, but cannot find any library for that. It doesn't seem difficult but it feels like reinventing the wheel.
In XML there are so many tutorials showing how to traverse an XML tree with DOM :(
A JSON object is simply a Javascript object. That's actually what JSON stands for: JavaScript Object Notation. So you'd traverse a JSON object however you'd choose to "traverse" a Javascript object in general.
In jQuery, I'd do something like
$.each(myJsonObj, function(key,val){
// do something with key and val
});
You can always write a function to recursively descend into the object:
function traverse(jsonObj) {
if( typeof jsonObj == "object" ) {
$.each(jsonObj, function(k,v) {
// k is either an array index or object key
traverse(v);
}
}
else {
// jsonOb is a number or string
}
}
This should be a good starting point. I highly recommend using jQuery for such things, since their utilities such as the each loop make writing such code much easier.
If you think jQuery is kind of overkill
for such a primitive task, you could do something like that:
//your object
var o = {
foo:"bar",
arr:[1,2,3],
subo: {
foo2:"bar2"
}
};
//called with every property and it's value
function process(key,value) {
log(key + " : "+value);
}
function traverse(o,func) {
for (i in o) {
func.apply(this,[i,o[i]]);
if (typeof(o[i])=="object") {
//going on step down in the object tree!!
traverse(o[i],func);
}
}
//that's all... no magic, no bloated framework
traverse(o,process);
Depends on what you want to do. Here's an example of traversing a JavaScript object tree, printing keys and values as it goes:
function js_traverse(o) {
var type = typeof o
if (type == "object") {
for (var key in o) {
print("key: ", key)
js_traverse(o[key])
}
} else {
print(o)
}
}
js> foobar = {foo: "bar", baz: "quux", zot: [1, 2, 3, {some: "hash"}]}
[object Object]
js> js_traverse(foobar)
key: foo
bar
key: baz
quux
key: zot
key: 0
1
key: 1
2
key: 2
3
key: 3
key: some
hash
there's a missing } in the traverse function above. Corrected version:
function traverse(o,func) {
for (i in o) {
func.apply(this,[i,o[i]]);
if (typeof(o[i])=="object") {
//going on step down in the object tree!!
traverse(o[i],func);
}
}
}