I agree with @KaeVerens, this is (or was) badly structured JSON. Besides the array that isn't an array, there's an extra level of object you don't appear to need. If you're generating the JSON, it would make a lot more sense if it were this instead:
{
"nodes": [
{ "title": "test", "field2": "test2" },
{ "title": "test3", "field2": "test4" }
]
}
OK, updating now that your JSON data looks more like this. But now what you posted isn't valid JSON at all! It's a JavaScript object that will work in the console or in test code, but it won't pass a JSON validator. The property names aren't quoted as they should be, and there's a ;
at the end. It should look like:
{
"nodes": [
{ "title": "test" },
{ "title": "test2" },
{ "title": "test3" },
{ "title": "test4" }
]
}
(Spacing and indentation don't matter; I just formatted it this way for clarity.)
Anyway, with that fixed, this code works fine on your current data:
$.each( data.nodes, function( index, node ) {
console.log( node.title );
});
And your for
loop would work fine if you check the length of the actual nodes
array instead of checking data.length
which doesn't exist:
var nodes = data.nodes;
for( var i = 0, len = nodes.length; i < len; i++ ) {
var node = nodes[i];
console.log( node.title );
}
I recommend taking references to nested objects as this code does (the nodes
and node
variables) instead of stuff like data.nodes[i]
. Much easier to keep track of, and it can be more efficient too (although it wouldn't be any different in this simple case).