1

I have a json data coming from rest in following format:

{
"status_code": 200, 
"data": {
"units": -1, 
"unit_reference_ts": null,
"tz_offset": -4,
"unit": "day", 
"countries": [{"country": "IN", "clicks": 12}]}, 
"status_txt": "OK"
}

I want to access the countries part and need to generate data in format like

{"IN":12, ......}

I dont know how to iterate through javascript, JSON array? Please help i am confused between methods which is the best & easiest that will work throughout the JSON?

I tried this:

 $.each(response.countries, function(key, value) {
 console.log(value.country + ": " + value.clicks);});

but it is showing me type error e is undefined...

4
  • possible duplicate of Parse JSON in JavaScript? Commented Apr 27, 2015 at 13:55
  • Is it JSON, or is it an object, there's a difference ? Commented Apr 27, 2015 at 13:55
  • Possible duplicate of stackoverflow.com/questions/3010840/… Commented Apr 27, 2015 at 13:57
  • its JSON data coming through url on request Commented Apr 27, 2015 at 14:01

1 Answer 1

2

Make sure you parse your JSON first (var data = JSON.parse(json)), then use a simple loop:

var obj = {};
for (var i = 0, l = data.data.countries.length; i < l; i++) {
    var tmp = data.data.countries[i];
    obj[tmp.country] = tmp.clicks
}

console.log(obj); // { IN: 12, UK: 123 }

DEMO

Since (from your edit) you're using jQuery, you'll probably need to do this (note that jQuery automatically parses JSON data if you retrieve it using one of its AJAX methods):

var obj = {};
$.each(response.data.countries, function(key, value) {
    obj[value.country] = value.clicks;
});

If you want a string instead of an object, just JSON.stringify the obj:

var json = JSON.stringify(obj);

DEMO

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.