2015-09-13 47 views
0

我想從下面的json中獲取subdivisions.names.en,但不斷收到「TypeError:location.subdivisions.names is undefined」錯誤。我敢肯定它的東西簡單&概率只是需要更多的睡眠;)如何從json中提取特定信息

我能得到其他我需要的信息 - 這工作:

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

但這並不:

alert(location.subdivisions.names.en); 

這裏是我的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 
     } 
    ], 
} 

回答

3

"subdivisions": [ ...表示該變量是一個對象數組。你需要指數之條目:

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

請注意,不能有任何條目

"subdivisions": [], ...

和他們中的很多,所以必須有一些邏輯/檢查的指數。

location.subdivisions.length可能有助於

+0

我必須得到更多的睡眠 - 謝謝你:) – MWD

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.

這就是說,location.subdivisions.names.en未定義的原因是因爲在您的JSON中它不存在。

subdivisions也是一個對象數組。

爲了訪問您正在嘗試的操作,您必須使用subdivisions[0].names.en

+1

我認爲問題並不清楚。它看起來像位置是一個變量,這個JSON被分配給(看看什麼是有效的,什麼是包含在位置,你會明白我的意思)。我相信真正的問題是,細分是一個數組... – user3334690

+0

我認爲'位置'在json給定的上下文中必須解決'location.location。〜' –

+1

我會appreaciate如果誰downvoted給出了一個理由我已經解決了答案。 – GiamPy

2

「細分」被定義爲您的JSON文件的數組。根據意圖,將其改爲只是散列(刪除方括號)或修改訪問權限

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

偉大的信息 - 謝謝你:) – MWD