嵌套的JSON对象 - 我是否必须使用数组? [英] Nested JSON objects - do I have to use arrays for everything?

查看:172
本文介绍了嵌套的JSON对象 - 我是否必须使用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在JSON中使用嵌套对象,所以我不必从所有内容中创建数组?为了使我的对象无错误地解析,我似乎需要这样的结构:

Is there any way to have nested objects in JSON so I don't have to make arrays out of everything? For my object to be parsed without error I seem to need a structure like this:

{"data":[{"stuff":[
    {"onetype":[
        {"id":1,"name":"John Doe"},
        {"id":2,"name":"Don Joeh"}
    ]},
    {"othertype":[
        {"id":2,"company":"ACME"}
    ]}]
},{"otherstuff":[
    {"thing":
        [[1,42],[2,2]]
    }]
}]}

如果我将此对象提取到名为result的变量中,我必须像这样访问嵌套对象: / p>

If I fetch this object into a variable called "result" I have to access the nested objects like this:

result.data[0].stuff[0].onetype[0]

result.data[1].otherstuff[0].thing[0]

这对我来说似乎很笨拙和多余,如果可能,我会首选:

This seems clumsy and redundant to me, if possible I would prefer:

result.stuff.onetype[0]

result.otherstuff.thing

但我怎么能当一切都是数组时,直接使用对象键?对于我这种困惑和未受过教育的人来说,这样的事情似乎更合适:

But how can I use the object keys directly when everything is an array? To my confused and uneducated mind something like this would seem more appropriate:

{"data":
    {"stuff":
        {"onetype":[
            {"id":1,"name": ""},
            {"id":2,"name": ""}
        ]}
        {"othertype":[
            {"id":2,"xyz": [-2,0,2],"n":"Crab Nebula","t":0,"c":0,"d":5}
        ]}
    }
    {"otherstuff":
        {"thing":
            [[1,42],[2,2]]
        }
    }
}

我可能在这里误解了一些基本的东西,但我无法获得jQuery解析器(也不是jQuery 1.4使用的本机FF解析器)来接受第二个样式对象。如果有人能够启发我,将不胜感激!

I've probably misunderstood something fundamental here, but I cannot get the jQuery parser (nor the native FF parser used by jQuery 1.4) to accept the second style object. If anyone can enlighten me it would be gratefully appreciated!

推荐答案

您不需要使用数组。

JSON值可以是数组,对象或基元(数字或字符串)。

JSON values can be arrays, objects, or primitives (numbers or strings).

您可以像这样编写JSON:

You can write JSON like this:

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": [[1,42],[2,2]]
     }
}

您可以像这样使用它:

obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1]  //thing is a nested array or a 2-by-2 matrix.
                            //I'm not sure whether you intended to do that.

这篇关于嵌套的JSON对象 - 我是否必须使用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆