javascript 如何在具有动态键值对的javascript中解析json?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31285360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse json in javascript having dynamic key value pair?
提问by Amit Das
I want to parse a JSON string in JavaScript. The response is something like
我想用 JavaScript 解析一个 JSON 字符串。响应类似于
var response = '{"1":10,"2":10}';
How can I get the each key and value from this json ?
我怎样才能从这个 json 中获取每个键和值?
I am doing this -
我在做这个——
var obj = $.parseJSON(responseData);
console.log(obj.count);
But i am getting undefined
for obj.count
.
但我得到undefined
了obj.count
。
回答by TaoPR
To access each key-value pair of your object, you can use Object.keys
to obtain the array of the keys which you can use them to access the value by [ ] operator. Please see the sample code below:
要访问对象的每个键值对,您可以使用Object.keys
获取键的数组,您可以使用它们通过 [ ] 运算符访问值。请参阅下面的示例代码:
Object.keys(obj).forEach(function(key){
var value = obj[key];
console.log(key + ':' + value);
});
Output:
输出:
1 : 10
2 : 20
1 : 10
2 : 20
Objects.keys
returns you the array of the keys in your object. In your case, it is ['1','2']
. You can therefore use .length
to obtain the number of keys.
Objects.keys
返回对象中的键数组。在你的情况下,它是['1','2']
。因此,您可以使用.length
来获取密钥的数量。
Object.keys(obj).length;
回答by Marcos Pérez Gude
So you need to access it like an array, because your keys are numbers. See this fiddle:
所以你需要像数组一样访问它,因为你的键是数字。看到这个小提琴:
You can access like this:
您可以这样访问:
result[1] // this returns 10
result.1 // this returns an error
Good luck
祝你好运