问题描述
我想解析JavaScript中的JSON字符串.响应就像
I want to parse a JSON string in JavaScript. The response is something like
var response = '{"1":10,"2":10}';
如何从此json获取每个键和值?
How can I get the each key and value from this json ?
我正在这样做-
var obj = $.parseJSON(responseData);
console.log(obj.count);
但是我得到undefined
的obj.count
.
推荐答案
要访问对象的每个键值对,可以使用Object.keys
获取键的数组,您可以使用键数组访问值由[]运算符.请参见下面的示例代码:
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(obj).forEach(function(key){
var value = obj[key];
console.log(key + ':' + value);
});
输出:
2:20
Objects.keys
返回您对象中键的数组.您的情况是['1','2']
.因此,您可以使用.length
来获取键的数量.
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.
Object.keys(obj).length;
这篇关于如何解析具有动态键值对的javascript中的json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!