2

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 :)

4 Answers 4

8

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

myObjectFromJSON.someStuff[""].foo
Sign up to request clarification or add additional context in comments.

Comments

5

Try this:

data.someStuff[''].foo  

http://jsfiddle.net/GSWg9/

Comments

1
$(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/

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.