【问题标题】:How to walk through json response?如何遍历json响应?
【发布时间】:2012-02-26 01:08:39
【问题描述】:

我有这个 json 响应,我试图用它来获取天气条件,例如“湿度”和“temp_C”等。我尝试了一些方法,但没有奏效。

({ "data" : { "current_condition" : [ { "cloudcover" : "50",
            "humidity" : "44",
            "observation_time" : "12:10 AM",
            "precipMM" : "0.0",
            "pressure" : "1013",
            "temp_C" : "-2",
            "temp_F" : "29",
            "visibility" : "16",
            "weatherCode" : "116",
            "weatherDesc" : [ { "value" : "Partly Cloudy" } ],
            "weatherIconUrl" : [ { "value" : "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png" } ],
            "winddir16Point" : "W",
            "winddirDegree" : "280",
            "windspeedKmph" : "24",
            "windspeedMiles" : "15"
          } ],
      "request" : [ { "query" : "Rochester, United States Of America",
            "type" : "City"
          } ],
      "weather" : [ { "date" : "2012-02-25",
            "precipMM" : "2.2",
            "tempMaxC" : "-1",
            "tempMaxF" : "31",
            "tempMinC" : "-5",
            "tempMinF" : "24",
            "weatherCode" : "116",
            "weatherDesc" : [ { "value" : "Partly Cloudy" } ],
            "weatherIconUrl" : [ { "value" : "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png" } ],
            "winddir16Point" : "W",
            "winddirDegree" : "281",
            "winddirection" : "W",
            "windspeedKmph" : "54",
            "windspeedMiles" : "34"
          } ]
    } })

我试过这些:

$.getJSON(urlFromMyAPI, function (data) {
    alert(data.current_condition.temp_C);
    alert(data.temp_C);
    alert(data[current_condition].temp_C);
    // I also use loop
    for (i = 0; i <= 3; i++) {
        alert(data.current_condition[i])
    }
});
};

【问题讨论】:

  • 是你数据里的那个数据,还是你粘贴了什么?
  • 不确定我得到了你的问题,但这个数据是从世界天气在线 api 返回的。

标签: jquery json api


【解决方案1】:

我认为您的主要问题是您的数据嵌套在一个名为 data 的对象中,因此您需要额外级别的引用才能进入其中。当您像这样格式化您的响应时,也更容易看到您得到了什么,这样您就可以更清楚地看到嵌套的对象和数组:

({ "data": { 
    "current_condition": [ 
        {
            "cloudcover": "50", 
            "humidity": "44", 
            "observation_time": "12:10 AM", 
            "precipMM": "0.0", 
            "pressure": "1013", 
            "temp_C": "-2", 
            "temp_F": "29", 
            "visibility": "16", 
            "weatherCode": "116",  
            "weatherDesc": [ 
                {"value": "Partly Cloudy" } 
            ],  
            "weatherIconUrl": [ 
                {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png" } 
            ], 
            "winddir16Point": "W", 
            "winddirDegree": "280", 
            "windspeedKmph": "24", 
            "windspeedMiles": "15" 
        } 
    ],  
    "request": [ 
        {"query": "Rochester, United States Of America", "type": "City" } 
    ],  
    "weather": [
        {
            "date": "2012-02-25", 
            "precipMM": "2.2", 
            "tempMaxC": "-1", 
            "tempMaxF": "31", 
            "tempMinC": "-5", 
            "tempMinF": "24", 
            "weatherCode": "116",  
            "weatherDesc": [ 
                {"value": "Partly Cloudy" } 
            ],  
            "weatherIconUrl": [
                {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png" } 
            ], 
            "winddir16Point": "W", 
            "winddirDegree": "281", 
            "winddirection": "W", 
            "windspeedKmph": "54", 
            "windspeedMiles": "34" 
        } 
    ] 
}
})

也就是说,如果你想获取当前条件temp_C,应该是这样的(注意我为你的匿名函数更改了参数名称,以使代码不那么混乱):

$.getJSON( urlFromMyAPI, function(response){
    var temp = response.data.current_condition[0].temp_C;
});

如果你想把 temp 作为一个数字,你可能需要这样做:

$.getJSON( urlFromMyAPI, function(response){
    var temp = parseInt(response.data.current_condition[0].temp_C, 10);
});

【讨论】:

  • 它有效,伙计。不能给你 +1 我没有声誉:)
  • @user1233225 - 经过适当的时间后,您可以点击您最喜欢的答案旁边的复选标记,将其标记为最佳答案,您还将获得一些声誉积分。跨度>
【解决方案2】:

要遍历包含在JSON 对象中的数组,您需要访问data.data.current_condition

for(i = 0; i <= 3; i++){
   alert(data.data.current_condition[i]);

   var properties = data.data.current_condition[i];

   for(var y in properties)
       alert(properties[y]);
}

http://jsfiddle.net/m7TZx/

【讨论】:

    【解决方案3】:

    您的代码有两个问题。

    1. 您的变量称为数据,JSON 中的第一件事是一个称为数据的对象。
    2. current_condition 是一个对象数组(在Javascript中,方括号[]指的是一个数组,大括号{}指的是一个对象),所以在指temp_C之前必须说current_condition[index]。

    在这个例子中我将data重命名为json_data以避免混淆:

    $.getJSON( urlFromMyAPI, function(json_data){
        console.log(json_data.data.current_condition[0].temp_C);
    });
    

    如果您有多个 current_condition 对象,您可以使用 for 循环遍历它们:

    $.getJSON( urlFromMyAPI, function(json_data){
        var current_conditions = json_data.data.current_condition;
        for(var i=0; i < current_conditions.length; i++) {
            console.log(current_conditions.temp_C);
        }
    });
    

    如果您想以更好的格式查看它,可以使用 Javascript 美化器(例如 http://jsbeautifier.org/)。

    您可能会发现console.logalert 更有用。大多数浏览器都有一个控制台,在谷歌浏览器中,您可以通过按F12 并单击控制台来找到它。

    【讨论】:

      【解决方案4】:

      JSON 不应包含在“()”中,除非在打开“(”之前将其作为带有函数名称的 jsonp 发送。现在假设您从指向 jsonp url 的浏览器复制了响应以及什么是粘贴是复制错误。

      使用 $.each 使得循环非常容易。

      $.each( data.data.current_condition[0], function ( key, value){
          console.log( 'Key:', key, ' Value:', value)
      })
      

      【讨论】:

        猜你喜欢
        • 2014-10-30
        • 1970-01-01
        • 1970-01-01
        • 2020-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-29
        • 1970-01-01
        相关资源
        最近更新 更多