0

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?

  • Hi, I need to generate similar json response in c#. Can you please help me out this. I have posted my question here.http://stackoverflow.com/questions/10106716/linq-to-json-response/10106774#comment12949266_10106774 – ashish.chotalia Apr 11 '12 at 14:50

2 Answers2

3
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" */
  }
}
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • Thanks Calderan - It just wasn't making any sense when I was looking at other examples of navigating arrays. Cheers :) – user1326488 Apr 12 '12 at 10:22
0

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);
})
Nauman Bashir
  • 1,732
  • 3
  • 18
  • 26