简体   繁体   English

访问Javascript JSON嵌套对象

[英]Accessing Javascript json nested object

I have a json that looks like this 我有一个看起来像这样的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 
  },
}

I tried accessing the values in the json this way. 我尝试以这种方式访问​​json中的值。

JSON.stringify(tlist.toString("utf8"))

        for(var i = 0; i < tlist.length; i++){
        var totalCity = tlist[i]['match counts'];
        console.log(totalCity)
      } 

But i get an error that says undefined. 但我得到一个错误,说未定义。 Can anyone please point me to the problem? 谁能指出我的问题吗?

Thanks you. 谢谢。

The input object is not an array (or an array like object). 输入对象不是数组(或类似对象的数组)。 Hence it hasn't any property called length . 因此,它没有任何称为length属性。 It's just an object literal with key/value pairs. 它只是具有键/值对的对象文字。 So you have to parse it as you would have done with every other valid json and then loop through it's keys, like below: 因此,您必须像解析所有其他有效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); } 

Update 更新资料

Generally when we loop through the keys of an object, as correctly Patrick pointed out in his comment, we follow the pattern below: 通常,当我们遍历对象的键时,正如Patrick在其评论中正确指出的那样,我们遵循以下模式:

for(var key in obj){
    if(obj.hasOwnProperty(key)){
        // ....
    }
}

We do need this extra check, in order to avoid enumerating the properties that are defined on the object in the prototype chain of obj . 为了避免枚举在obj原型链中的对象上定义的属性,我们确实需要进行此额外检查。 At this case, since you object is a simple object whose proto is the Object, this is not needed. 在这种情况下,由于您的对象是一个简单的对象,其原型是对象,因此不需要。 This is the reason I didn't include it. 这就是我没有包含它的原因。

For an in depth analysis of this, please ave a look at the following links: 要对此进行深入分析,请查看以下链接:

That's not an array. 那不是数组。 You will have to access with it's key. 您将必须使用它的钥匙进行访问。

var x = {
  "0": {a: 'b'},
  "1": {a: 'b'},
}

for(key in x) {
  console.log(x[key]) //outputs {a: 'b'}
}

The key values in your object are string typed: 对象中的键值是string类型:

{   // Keys wrapped in "" are strings
    "1": { ... },
    "2": { ... }
}

Even though javascript is a non-strictly typed language, it still has internal types, and objects won't attempt to convert the accessing key types, they will perform a strict check on the keys to determine whether it exists. 即使javascript是非严格类型的语言,它仍然具有内部类型,并且对象不会尝试转换访问键的类型,但它们将对键进行严格检查以确定它是否存在。 When a strict check occurs, the value is not only taken into consideration, but so is the type; 进行严格检查时,不仅要考虑值,还要考虑类型。 it's the difference between == and === , for a === to evaluate to true both the value AND the type have to match. 它是=====的区别,对于=== ,值和类型都必须匹配为true

But when you go to access them in your loop, you're trying to access with a number type: 但是,当您在循环中访问它们时,您尝试使用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'];
    ...
}

But don't fret, you can still keep your loop, you just need to convert i to the correct type when you're accessing your object! 但是请不要担心,您仍然可以保持循环,只需在访问对象时将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'];
    ...
}

This will work: Please put a link to jquery, or use the script link below. 这将起作用:请放入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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM