jQuery将解析后的JSON分配给变量

时间:2014-07-10 16:04:42

标签: javascript jquery html ajax json

我知道这是一个非常简单的问题,但我正在努力解决它。以下是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中的标题值分配给变量&#39; title&#39;。我该怎么做?

感谢。

3 个答案:

答案 0 :(得分:2)

forecastday是一个数组,所以你需要使用index to element。

使用

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

但是,您可以简单地使用点符号

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

答案 1 :(得分:1)

仍然有点像菜鸟,但这可能有效:

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

答案 2 :(得分:1)

最好在这里使用点符号,并确保使用数组的corrent元素:

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

DEMO