LauraNMS LauraNMS - 5 months ago 30
Javascript Question

parsing nested json object

I have a json file that I'm trying to get values out of. One object is nested inside another in this file. I can isolate the top level values, but not the nested values. It must be a syntax issue. Here's what I'm using.

This is the json:

{
"total": [
[
{
"votes": "79,060"
},
{
"percent": "11%"
},
{
"winner": "0"
}
],
[
{
"votes": "167,800"
},
{
"percent": "22%"
},
{
"winner": "0"
}
],
[
{
"votes": "51,519"
},
{
"percent": "7%"
},
{
"winner": "0"
}
],
[
{
"votes": "297,060"
},
{
"percent": "39%"
},
{
"winner": "1"
}
],
[
{
"votes": "156,787"
},
{
"percent": "21%"
},
{
"winner": "0"
}
]
],
"useWinnerColors": 1,
"timestamp": "3:00 p.m. April 26",
"candidateCount": 5
}


When I write:

console.log(json.candidateCount);


I get the right answer (5).

But when I write:

console.log(json.total[0][1]);


I get Object { percent="11%"}.

And when I write:

console.log(json.total[0].votes);


I get undefined.

How do I isolate the value of the items in "total", please?

Answer

You're getting undefined because json.total[0] is itself, an array. You need to isolate the specific array inside json.total[0]. So you would need to do something like json.total[0][0].votes or json.total[0][1].votes.

I think a better structure for your JSON would be something like this:

{"total": [    
   {
      "votes": "79,060"
      "percent": "11%"
      "winner": "0",
   },
   ...
   {
      "votes": "156,787",
      "percent": "21%",
      "winner": "0"
   }], 
   "useWinnerColors": 1,
   "timestamp": "3:00 p.m. April 26",
   "candidateCount": 5
}

Now you can do json.total[0].votes.

You don't need to create an array where each entry is a name-value pair. You can directly use an associative-array.

EDIT: To iterate over your associative array, use for..in along with hasOwnProperty(). The hasOwnProperty() check will prevent you from iterating over properties that it has inherited (some third-party libraries pollute the namespace):

var map = json.total[0];
for(var prop in map) if(map.hasOwnProperty(prop)) {
   var value = map[prop];
   ...
}