How do I navigatin nested json data

90 views Asked by At

I need a little help with navigating a json file.

I'm looking to get all the country names from a return like this:

[{"country":
    {
     "225":["United Kingdom","Europe"],
     "206":["Switzerland","Europe"],
     "176":["Romania","Europe"],
     "127":["Madagascar","AMEA"],
     "217":["Tunisia","AMEA"]
    }
  }]

How would I get to this when I don't know or have a list of the 225, 206...etc?

2

There are 2 answers

1
Fabrizio Calderan On BEST ANSWER
var arr = [
    {
       "country": {
            "225":["United Kingdom","Europe"],
            "206":["Switzerland","Europe"],
            "176":["Romania","Europe"],
            "127":["Madagascar","AMEA"],
            "217":["Tunisia","AMEA"]
       }
    }
]

if you have a key (e.g. 225), then arr[0]["country"]["225"] returns an array with ["United Kingdom","Europe"]

if you want to obtain a list of keys (and respective values) just use

var countryObj = arr[0]["country"];
for (key in countryObj) {
   if (countryObj.hasOwnProperty(key)) {
      console.log(key);                /* e.g. 206 */ 
      console.log(countryObj[key]);    /* e.g. ["Switzerland","Europe"] */
      console.log(countryObj[key][0]); /* e.g. "Switzerland" */
  }
}
0
Nauman Bashir On

you can use it as an array as well,

in case you dont know the keys 255,256 and want to get the countries only, then probably a good way is to treverse the jquery object us the jquery

$(arr[0]["country"]).each(function(key,country){
  alert(country);
})