Tuesday, 13 December 2016

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





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.


Answer



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;

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...