Reputation: 3
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
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
Upvotes: 1
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