11

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.

Amit Das
  • 1,077
  • 5
  • 17
  • 44

2 Answers2

16

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;
Community
  • 1
  • 1
TaoPR
  • 5,932
  • 3
  • 25
  • 35
5

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

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69