本文介绍了如何解析具有动态键值对的javascript中的json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析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);

但是我得到undefinedobj.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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:14
查看更多