如何编写嵌套的多维JSON对象 [英] How to write a nested multi dimensional json object
本文介绍了如何编写嵌套的多维JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究json,我想知道这是否是编写嵌套的多维json对象的正确方法.我写道:
I am studying json and i was wondering if this is the right way to write a multi dimensional json object that is nested.I wrote:
var foo = {
"logged_in":true,
"town":"Dublin",
"state":"Ohio",
"country":"USA",
"products":2,
"0":{
"pic_id":"1500",
"description":"Picture of a computer",
"localion":"img.cloudimages.us/2012/06/02/computer.jpg",
"type":"jpg",
"childrenimages":2
"0":{
"pic_id":"15011",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
}
"1":{
"pic_id":"15012",
"description":"Picture of a cpu two",
"localion":"img.cloudimages.us/2012/06/02/thiscpu.png",
"type":"png"
}
},
"1":{
"pic_id":"1501",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/cpu.png",
"type":"png"
}
};
这是对的还是如果我的对象嵌套得太深我应该遵循的约定吗?
Is this right or is there a convention i should follow if my object becomes too deeply nested.
推荐答案
考虑使用数组而不是数字对象.
Consider using arrays instead of numerated object.
json中的数组使用[]定义 http://www.json.org/
Arrays in json are defined using [] http://www.json.org/
这里是一个例子:
var foo = {
"logged_in":true,
"town":"Dublin",
"state":"Ohio",
"country":"USA",
"products":
[
{
"pic_id":"1500",
"description":"Picture of a computer",
"localion":"img.cloudimages.us/2012/06/02/computer.jpg",
"type":"jpg",
"childrenimages":
[
{
"pic_id":"15011",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
},
{
"pic_id":"15012",
"description":"Picture of a cpu two",
"localion":"img.cloudimages.us/2012/06/02/thiscpu.png",
"type":"png"
}
]
},
{
"pic_id":"1501",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/cpu.png",
"type":"png"
}
],
};
(如果我忘记关闭{或[或,在SO:p中很难键入代码,请原谅我.)
(Forgive me if I forgot either closing { or [ or , its pretty hard to type code in SO :p )
这样,您甚至不需要像这样的计数
This way you dont even need to have counts like
"products":2,
或
"childrenimages":2
您只需
foo.products.length
或
foo.products[0].childrenimages.length
祝你好运:)
这篇关于如何编写嵌套的多维JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文