Reputation: 615
I get the following JSON returned from the server
{
"someStuff": {
"": {
"foo": 0
},
"moreStuff": {
"foo": 2
}
}
}
As you can see the first node in someStuff is not named.
Is there a way to handle this is JavaScript, eg, how can I select a node which has no name?
I know that the proper solution is to name the node in the code which generates the JSON, but I am looking for a dirty fix till I can contact the developer :)
Upvotes: 2
Views: 494
Reputation: 887
The trick is to use the [] operator like in the example below:
a = $.parseJSON('\
{\
"someStuff": {\
"": {\
"foo": 0\
},\
"moreStuff": {\
"foo": 2\
}\
}\
}\
');
a.someStuff[''].foo === 0 // returns true
Upvotes: 1
Reputation: 218852
$(function(){
var data={ "someStuff": {
"": { "foo": 0 },
"moreStuff": {"foo": 2 }
}
}
$.each(data.someStuff,function(index,item){
alert(item.foo);
});
});
Sample : http://jsfiddle.net/kshyju/hURDH/4/
Upvotes: 1
Reputation: 43872
.foo
is the same as ["foo"]
, so use []
whenever the name is not an identifier.
myObjectFromJSON.someStuff[""].foo
Upvotes: 8