2011-09-16 22 views
0

我有这样一个JSON:为什么我在获取json.length时未定义?

{"result":{"sandbox":1,"0":{"id":1106,"url":"http:\/\/www.example.com\/index1.html"},"1":{"id":9655,"url":"http:\/\/www.example.com\/index2.html"},"2":{"id":8447,"url":"http:\/\/www.example.com\/index3.html"}}} 

,我检索,然后这样做:

var json = JSON.parse(data); 
console.log(json.length); 

但控制台输出“不确定”,即使当我刚登录(JSON)它显示了我的对象。为什么?我怎样才能得到这个长度?我需要它for循环

回答

0

该json不是一个数组,所以你不会得到长度。

如果JSON有像[1,2,3]那么它是一个数组

您可以使用Online Parser

得到 console.log(json.result)

0

该JSON文档中的根级元素是一个对象,而不是一个数组。一个对象没有长度属性。相反,你可以只打印出整个对象:

console.log(json); 

请注意,你应该使用数组,而不是数字键的对象,像这样:

{"result": 
    {"sandbox":1, 
    "results": [ 
     {"id":1106,"url":"http:\/\/www.example.com\/index1.html"}, 
     {"id":9655,"url":"http:\/\/www.example.com\/index2.html"}, 
     {"id":8447,"url":"http:\/\/www.example.com\/index3.html"} 
    ] 
    } 
} 

通过这种改进JSON,你可能会输出:

console.log(modifiedJson.result.results.length);