erik404
erik404

Reputation: 615

JSON object returned without name

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

Answers (4)

wojcikstefan
wojcikstefan

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

Shyju
Shyju

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

Ram
Ram

Reputation: 144719

Try this:

data.someStuff[''].foo  

http://jsfiddle.net/GSWg9/

Upvotes: 5

Kevin Reid
Kevin Reid

Reputation: 43872

.foo is the same as ["foo"], so use [] whenever the name is not an identifier.

myObjectFromJSON.someStuff[""].foo

Upvotes: 8

Related Questions