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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:35:19  来源:igfitidea点击:

How to parse json in javascript having dynamic key value pair?

javascriptjson

提问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 undefinedfor obj.count.

但我得到undefinedobj.count

回答by TaoPR

To access each key-value pair of your object, you can use Object.keysto 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.keysreturns you the array of the keys in your object. In your case, it is ['1','2']. You can therefore use .lengthto 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:

所以你需要像数组一样访问它,因为你的键是数字。看到这个小提琴:

https://jsfiddle.net/7f5k9het

https://jsfiddle.net/7f5k9het

You can access like this:

您可以这样访问:

 result[1] // this returns 10
 result.1 // this returns an error

Good luck

祝你好运