[英]Accessing Javascript json nested object
我有一个看起来像这样的json
{
"1": {
"average percent match": 0.2916666667,
"match counts": 1.0,
"confidence": 0.25
},
"0": {
"average percent match": 0.25,
"match counts": 1.0,
"confidence": 0.25
},
}
我尝试以这种方式访问json中的值。
JSON.stringify(tlist.toString("utf8"))
for(var i = 0; i < tlist.length; i++){
var totalCity = tlist[i]['match counts'];
console.log(totalCity)
}
但我得到一个错误,说未定义。 谁能指出我的问题吗?
谢谢。
输入对象不是数组(或类似对象的数组)。 因此,它没有任何称为length
属性。 它只是具有键/值对的对象文字。 因此,您必须像解析所有其他有效json一样解析它,然后遍历它的键,如下所示:
var input = "{\\"1\\": { \\"average percent match\\": 0.2916666667, \\"match counts\\": 1.0, \\"confidence\\": 0.25 }, \\"0\\": { \\"average percent match\\": 0.25, \\"match counts\\": 1.0, \\"confidence\\": 0.25 } }"; var obj = JSON.parse(input); for(var key in obj){ var totalCity = obj[key]['match counts']; console.log(totalCity); }
更新资料
通常,当我们遍历对象的键时,正如Patrick在其评论中正确指出的那样,我们遵循以下模式:
for(var key in obj){
if(obj.hasOwnProperty(key)){
// ....
}
}
为了避免枚举在obj
原型链中的对象上定义的属性,我们确实需要进行此额外检查。 在这种情况下,由于您的对象是一个简单的对象,其原型是对象,因此不需要。 这就是我没有包含它的原因。
要对此进行深入分析,请查看以下链接:
那不是数组。 您将必须使用它的钥匙进行访问。
var x = {
"0": {a: 'b'},
"1": {a: 'b'},
}
for(key in x) {
console.log(x[key]) //outputs {a: 'b'}
}
对象中的键值是string
类型:
{ // Keys wrapped in "" are strings
"1": { ... },
"2": { ... }
}
即使javascript是非严格类型的语言,它仍然具有内部类型,并且对象不会尝试转换访问键的类型,但它们将对键进行严格检查以确定它是否存在。 进行严格检查时,不仅要考虑值,还要考虑类型。 它是==
和===
的区别,对于===
,值和类型都必须匹配为true
。
但是,当您在循环中访问它们时,您尝试使用number
类型进行访问:
// i is defined as the number 0, and incremented by 1 on each iteration
for(var i = 0; i < tlist.length; i++){
var totalCity = tlist[i]['match counts'];
...
}
但是请不要担心,您仍然可以保持循环,只需在访问对象时将i
转换为正确的类型即可!
for(var i = 0; i < tlist.length; i++){
// Adding an empty string to a number will convert said number into a string
var totalCity = tlist[i + '']['match counts'];
...
}
这将起作用:请放入jquery的链接,或使用下面的脚本链接。
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
var data = {
"1": {
"average percent match": 0.2916666667,
"match counts": 1.0,
"confidence": 0.25
},
"0": {
"average percent match": 0.25,
"match counts": 1.0,
"confidence": 0.25
},
}
var total =0;
$.each(data, function (i, item) {
total += item["match counts"];
});
alert("Total of match counts is: " + total);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.