Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to parse a JSON string in JavaScript. The response is something like

var response = '{"1":10,"2":10}';

How can I get the each key and value from this json ?

I am doing this -

var obj =  $.parseJSON(responseData);
console.log(obj.count);

But i am getting undefined for obj.count.

like image 876
Amit Das Avatar asked Jul 08 '15 06:07

Amit Das


2 Answers

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);
});

Output:

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.

Object.keys(obj).length;
like image 51
TaoPR Avatar answered Oct 27 '22 05:10

TaoPR


So you need to access it like an array, because your keys are numbers. See this fiddle:

https://jsfiddle.net/7f5k9het

You can access like this:

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

Good luck

like image 20
Marcos Pérez Gude Avatar answered Oct 27 '22 07:10

Marcos Pérez Gude