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 :)
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 :)
Share Improve this question asked Aug 6, 2012 at 20:33 erik404erik404 6151 gold badge7 silver badges23 bronze badges4 Answers
Reset to default 8.foo
is the same as ["foo"]
, so use []
whenever the name is not an identifier.
myObjectFromJSON.someStuff[""].foo
Try this:
data.someStuff[''].foo
http://jsfiddle/GSWg9/
$(function(){
var data={ "someStuff": {
"": { "foo": 0 },
"moreStuff": {"foo": 2 }
}
}
$.each(data.someStuff,function(index,item){
alert(item.foo);
});
});
Sample : http://jsfiddle/kshyju/hURDH/4/
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