0

I am trying to get the subdivisions.names.en from the json below but keep getting a "TypeError: location.subdivisions.names is undefined" error. I'm sure it something simple & prob just need more sleep ;)

I can get other the info I need - this works:

alert(location.city.names.en + ' ' + location.postal.code);

But this does not:

alert(location.subdivisions.names.en);

Here is my json:

{
    "continent": {
        "code": "OC",
        "geoname_id": xxx,
        "names": {
            "fr": "Océanie",
            "pt-BR": "Oceania",
            "zh-CN": "大洋洲",
            "es": "Oceanía",
            "de": "Ozeanien",
            "ja": "オセアニア",
            "en": "Oceania",
            "ru": "Океания"
        }
    },
    "location": {
        "longitude": xxxx,
        "latitude": -xxxx,
        "time_zone": "Australia/Melbourne"
    },
    "subdivisions": 
    [
        {
            "names": {
                "ru": "Виктория",
                "pt-BR": "Vitória",
                "en": "Victoria"
            },
            "iso_code": "VIC",
            "geoname_id": xxxx
        }
    ],
}
MWD
  • 1,632
  • 2
  • 18
  • 39

3 Answers3

3

"subdivisions": [ ... indicates, that this variable is an array of objects. You need to index the proper entry:

  alert(location.subdivisions[0].names.en);

Please be aware that there must not be any entry

"subdivisions": [], ...

and a lot of them, so there must be some logic / check on the index.

location.subdivisions.length might help

Axel Amthor
  • 10,980
  • 1
  • 25
  • 44
2

"subdivisions" is defined as an array in your json file. Depending on what is intended, either change it to be just a hash (remove the square brackets) or modify the access to

alert(location.subdivisions[0].names.en);
Laurowyn
  • 21
  • 4
0

You should have a look at what is JSON and how to use it properly because apparently you seem to lack the basic knowledge of how JSON is structured.

That being said, the reason why location.subdivisions.names.en is undefined is because in your JSON it does not exist.

subdivisions is also an array of objects.

In order to access what you are trying to you must use subdivisions[0].names.en.

Community
  • 1
  • 1
GiamPy
  • 3,543
  • 3
  • 30
  • 51
  • 1
    I think the question isn't clear. It looks like location is a variable that this json is being assigned to (look at what works and what is included in location and you'll see what I mean). I believe the actual issue is that subdivisions is an array... – user3334690 Sep 13 '15 at 20:57
  • I assume that `location` in the given context of the json must be addressed `location.location.~` – Axel Amthor Sep 13 '15 at 20:58
  • 1
    I'd appreaciate if whoever downvoted gave a reason since I have fixed the answer. – GiamPy Sep 13 '15 at 20:59