解析嵌套的json对象 [英] parsing nested json object
问题描述
我有一个json文件,我正试图从中获取值。一个对象嵌套在此文件中的另一个对象中。我可以隔离顶级值,但不能隔离嵌套值。它必须是语法问题。这是我正在使用的。
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.
这是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
}
当我写作:
console.log(json.candidateCount);
我得到了正确的答案(5)。
I get the right answer (5).
但是当我写的时候:
console.log(json.total[0][1]);
我得到对象{percent =11%}。
I get Object { percent="11%"}.
当我写:
console.log(json.total[0].votes);
我得到了未定义。
如何隔离总计项目的价值?
How do I isolate the value of the items in "total", please?
推荐答案
你得到 undefined
因为 json.total [0]
本身就是一个数组。你需要隔离 <$ em> c> json.total [0] 里面的特定数组。所以你需要做类似 json.total [0] [0] .votes
或 json.total [0] [1] .votes
。
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
.
我认为更好的结构你的JSON将是这样的:
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
}
现在你可以执行 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.
编辑:要迭代关联数组,请使用 for..in
以及 hasOwnProperty()
。 hasOwnProperty()
check将阻止您迭代它继承的属性(某些第三方库污染命名空间):
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];
...
}
这篇关于解析嵌套的json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!