我正在研究json,我想知道这是否是编写嵌套的多维json对象的正确方法。我写道:
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"
}
};
如果我的对象变得太嵌套了,我应该遵循这个约定吗?
答案 0 :(得分:22)
考虑使用数组而不是数字对象。
json中的数组是使用[]定义的 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),请原谅我
这样你甚至不需要像
这样的计数"products":2,
或
"childrenimages":2
您只需
foo.products.length
或
foo.products[0].childrenimages.length
祝你好运:)
答案 1 :(得分:1)
这是您数据的正确格式(注意我自己更改了一些数据)
{
"logged_in":true,
"town":"Dublin",
"state":"Ohio",
"country":"USA",
"products":2,
"productinfo":[
{
"0":{
"pic_id":"1500",
"description":"Picture of a computer",
"localion":"img.cloudimages.us/2012/06/02/computer.jpg",
"type":"jpg",
"childrenimages":2
},
"1":{
"pic_id":"15011",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
},
"2":{
"pic_id":"15012",
"description":"Picture of a cpu two",
"localion":"img.cloudimages.us/2012/06/02/thiscpu.png",
"type":"png"
},
"3":{
"pic_id":"1501",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/cpu.png",
"type":"png"
}
}
]
}
答案 2 :(得分:1)
这实际上并不是你在那里的数组,它只是一个包含属性的对象。你也错过了一些逗号,所以这甚至都不会编译。
在这种情况下,对您来说更方便的是使用数组和对象来形成您的JSON。例如:
var this_json_string = {
"state":"Ohio",
"country":"USA",
"products":[
{
"pic_id":"1500",
"description":"Picture of a computer",
},
{
"pic_id":"15011",
"description":"Picture of a cpu"
},
{
"pic_id":"15012",
"description":"Picture of a cpu two"
},
{
"pic_id":"1501",
"description":"Picture of a cpu"
}
]
};
答案 3 :(得分:-3)
不要写JSON。说真的,除了简单的配置文件外,不要编写JSON。
您可以使用实用程序将对象转换为大多数语言的JSON字符串(如果不是)。
PHP:json_encode($array);
Javascript:JSON.stringify( obj );
等
手动编写JSON通常会导致语法错误。在您看到缺少逗号或w / e之前,会让您头疼的那种。你有很好的工具来做到这一点,使用它们。您可以与XML进行比较,但是当您输入时,JSON没有工具(IDE,文本编辑器)说“这种语法错误”。例如,没有编辑会告诉您使用单引号而不是双引号。
只是不要写JSON。