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?
You’re getting
undefinedbecausejson.total[0]is itself, an array. You need to isolate the specific array insidejson.total[0]. So you would need to do something likejson.total[0][0].votesorjson.total[0][1].votes.I think a better structure for your JSON would be something like this:
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..inalong withhasOwnProperty(). ThehasOwnProperty()check will prevent you from iterating over properties that it has inherited (some third-party libraries pollute the namespace):