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
.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With