2014-07-10 44 views
-1

我知道這是一個非常簡單的問題,但我正在爲此付出努力。這裏是JSON的一個部分:jQuery將已分析的JSON分配給變量

"forecast": { 
    "txt_forecast": { 
     "date": "7:52 AM MDT", 
     "forecastday": [ 
     { 
      "period": 0, 
      "icon": "partlycloudy", 
      "icon_url": "http://icons.wxug.com/i/c/k/partlycloudy.gif", 
      "title": "Thursday", 
      "fcttext": "Partly cloudy. High near 90F. Winds W at 10 to 15 mph.", 
      "fcttext_metric": "Sunshine and clouds mixed. High 32C. Winds W at 15 to 25 kph.", 
      "pop": "10" 
     }, 
     { 
      "period": 1, 
      "icon": "nt_partlycloudy", 
      "icon_url": "http://icons.wxug.com/i/c/k/nt_partlycloudy.gif", 
      "title": "Thursday Night", 
      "fcttext": "Partly cloudy skies. Low 71F. Winds SSE at 5 to 10 mph.", 
      "fcttext_metric": "Partly cloudy. Low 22C. Winds SSE at 10 to 15 kph.", 
      "pop": "0" 
     }, 

這裏是我在我的網站代碼:

<script> 
     jQuery(document).ready(function($) { 
      $.ajax({ 
       url : "http://api.wunderground.com/api/b18485d6da512c58/geolookup/forecast/q/UT/SLC.json", 
       dataType : "jsonp", 
       success : function(parsed_json) { 
        var title = parsed_json['forecast']['txt_forecast']['forecastday']['period.0']['title']; 
        document.getElementById('day').innerHTML = title; 
        } 
      }); 
     }); 
    </script> 

我想週期0內以指定標題的值給變量「稱號」。我怎麼做?

謝謝。

+0

forcastday是一個數組,你必須指定你希望訪問哪個數組。 –

+0

首先檢查此鏈接(解釋必要的JSON):http://www.mkyong.com/javascript/how-to-access-json-object-in-javascript/ –

回答

2

forecastday是一個數組,所以你需要使用索引元素。

使用

var title = parsed_json['forecast']['txt_forecast']['forecastday'][0]['title']; 
                    ^............... 

然而,你可以簡單地使用點符號

var title = parsed_json.forecast.txt_forecast.forecastday[0].title; 
1

還是有點小白,但是這可能工作:

var title = parsed_json['forecast']['txt_forecast']['forecastday'][0].title; 
1

你最好不要在這裏使用點符號,並確保您使用數組的元素corrent:

var title = parsed_json.forecast.txt_forecast.forecastday[0].title; 

DEMO