最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSON object returned without name - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

4 Answers 4

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
发布评论

评论列表(0)

  1. 暂无评论