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.

3
  • 2
    To get the no. of elements count use Object.keys(obj).length Commented Jul 8, 2015 at 6:48
  • @Tushar And if i want key and value then how can i do this ? Commented Jul 8, 2015 at 6:50
  • stackoverflow.com/questions/684672/… Commented Jul 8, 2015 at 6:51

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.