简体   繁体   中英

Accessing Javascript json nested object

I have a json that looks like this

{
  "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.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 . 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:

 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:

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 . 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:

{   // 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. 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.

But when you go to access them in your loop, you're trying to access with a number type:

// 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!

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.

<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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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