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

查看:34
本文介绍了嵌套的 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"的变量中我必须像这样访问嵌套对象:

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天全站免登陆