0

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.

1
  • 1
    Use console.log(data) in the success callback to see the object you're getting. Commented Dec 9, 2015 at 13:20

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.