Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  70] [ 3]  / answers: 1 / hits: 31047  / 9 Years ago, wed, july 8, 2015, 12:00:00

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.


More From » json

 Answers
52

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;

[#65891] Sunday, July 5, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brockg

Total Points: 55
Total Questions: 104
Total Answers: 104

Location: Hungary
Member since Wed, Nov 9, 2022
2 Years ago
;