jingle
jingle

Reputation: 3

JSON get object index

I have this json file (data.json):

{
  "country":[{
    "Russia":[
      "Voronezh",
      "Moscow",
      "Vorkuta"
  ],
    "United Kingdom":[
      "London"
  ]
  }],
  "countryCodes":[
    "ru",
    "uk"
  ]
}

and such code:

$.getJSON('data.json', function success(data){
  alert(data.country[0]);
});

this returned "undefined". But i want get "Russia", and having indexes object Russia, i want get "Voronezh", don't use "data.country.Russia".

Sorry for my English.

Upvotes: 0

Views: 69

Answers (2)

Kunal.Bhatt
Kunal.Bhatt

Reputation: 73

Adding to ArgOn's answer where he has used Dot notation, there is one more way to get the answer i.e. by using Square bracket notation

var option = "countries";  (assign value to a variable)
data[option][0]["name"]; //Russia
data[option][0]["cities"][0]; //Voronezh
  • Dot notation is faster to write and clearer to read.
  • Square bracket notation allows access to properties containing special characters and selection of properties using variables.

Upvotes: 1

Arg0n
Arg0n

Reputation: 8423

If I were you, I would restructure the JSON to look something like this:

var data = {
    "countries": [
        {
            "name": "Russia",
            "cities": [
                "Voronezh",
                "Moscow",
                "Vorkuta"
            ]
        }, 
        {
            "name": "United Kingdom",
            "cities": [
                "London"
            ]
        }
    ],
    "countryCodes": [
        "ru",
        "uk"
    ]
}

data.countries[0].name; //Russia
data.countries[0].cities[0]; //Voronezh

Upvotes: 2

Related Questions