Joh*_*lze 101 javascript syntax jquery parsing json
有没有办法在JSON中使用嵌套对象,所以我不必从所有内容中创建数组?为了我的对象没有错误地解析我似乎需要这样的结构:
{"data":[{"stuff":[
{"onetype":[
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
]},
{"othertype":[
{"id":2,"company":"ACME"}
]}]
},{"otherstuff":[
{"thing":
[[1,42],[2,2]]
}]
}]}
Run Code Online (Sandbox Code Playgroud)
如果我将这个对象提取到一个名为"result"的变量中,我必须像这样访问嵌套对象:
result.data[0].stuff[0].onetype[0]
Run Code Online (Sandbox Code Playgroud)
和
result.data[1].otherstuff[0].thing[0]
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎很笨拙和多余,如果可能的话我宁愿:
result.stuff.onetype[0]
Run Code Online (Sandbox Code Playgroud)
和
result.otherstuff.thing
Run Code Online (Sandbox Code Playgroud)
但是当一切都是数组时,如何直接使用对象键?对于我困惑和未受过教育的人来说,这样的事情似乎更合适:
{"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]]
}
}
}
Run Code Online (Sandbox Code Playgroud)
我可能在这里误解了一些基本的东西,但我无法获得jQuery解析器(也不是jQuery 1.4使用的本机FF解析器)来接受第二个样式对象.如果有人能够启发我将非常感激!
SLa*_*aks 188
您不需要使用数组.
JSON值可以是数组,对象或基元(数字或字符串).
您可以像这样编写JSON:
{
"stuff": {
"onetype": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"othertype": {"id":2,"company":"ACME"}
},
"otherstuff": {
"thing": [[1,42],[2,2]]
}
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
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.
Run Code Online (Sandbox Code Playgroud)
每个对象都必须在父对象中命名:
{ "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]]
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以你不能声明这样的对象:
var obj = {property1, property2};
Run Code Online (Sandbox Code Playgroud)
它一定要是
var obj = {property1: 'value', property2: 'value'};
Run Code Online (Sandbox Code Playgroud)
您的jSON数据中有太多冗余的嵌套数组,但可以检索信息.虽然像其他人一样说过你可能想要清理它.
在另一个each()中使用each()包装直到最后一个数组.
对于result.data[0].stuff[0].onetype[0]在jQuery的你可以做到以下几点:
`
$.each(data.result.data, function(index0, v) {
$.each(v, function (index1, w) {
$.each(w, function (index2, x) {
alert(x.id);
});
});
});
Run Code Online (Sandbox Code Playgroud)
`