如何从json / jsonp结果中获取特定数据?

时间:2013-11-15 06:15:15

标签: jquery asp.net json jsonp response

我有一个来自Weather API的json响应。我想获得一个特定属性的数据,这是响应:

 {
    "response": {
        "version": "0.1",
        "termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
        "features": {
            "forecast": 1
        }
    },
    "forecast": {
        "txt_forecast": {
            "date": "2:00 PM PDT",
            "forecastday": [
                {
                    "period": 0,
                    "icon": "partlycloudy",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",
                    "title": "Tuesday",
                    "fcttext": "Partly cloudy in the morning, then clear. High of 68F. Breezy. Winds from the West at 10 to 25 mph.",
                    "fcttext_metric": "Partly cloudy in the morning, then clear. High of 20C. Windy. Winds from the West at 20 to 35 km/h.",
                    "pop": "0"
                },
                {
                    "period": 1,
                    "icon": "partlycloudy",
                    "icon_url": "http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",
                    "title": "Tuesday Night",
                    "fcttext": "Mostly cloudy. Fog overnight. Low of 50F. Winds from the WSW at 5 to 15 mph.",
                    "fcttext_metric": "Mostly cloudy. Fog overnight. Low of 10C. Breezy. Winds from the WSW at 10 to 20 km/h.",
                    "pop": "0"
                }......

我希望得到预测:txt_forecast:fcttext 我希望得到" fcttext"从上面的回复..我可以使用下面的代码得到日期。

 var date = parsed_json['forecast']['txt_forecast']['date'];

请帮助我如何获得" fcttext"从回应。

4 个答案:

答案 0 :(得分:1)

txt_forecast.forecastday是一个数组。数组的每个元素都是一个包含fcttext实例的对象。如果你想获得第一个元素,你可以这样做:

parsed_json['forecast']['txt_forecast']['forecastday'][0]['fcctext']

答案 1 :(得分:1)

试试这个:

for(var forcast_arr_index in parsed_json['forecast']['txt_forecast']['forcastday'])
    console.log(parsed_json['forecast']['txt_forecast']['forcastday'][forcast_arr_index]['fcctest']);

小心引号。

答案 2 :(得分:0)

尝试这样的事情

        var obj = jQuery.parseJSON(json);
        var forecastday_arr = obj.forecast.txt_forecast.forecastday;
        jQuery(forecastday_arr).each(function(i){
            var forecastday_obj = forecastday_arr[i];
            console.log(forecastday_obj);
        });

答案 3 :(得分:0)

你可能想要做这样的事情,因为 fcttext forecastday 内,而 forecastday Array。 ..

$.each(parsed_json.forecast.txt_forecast.forecastday, function(key, object){
     console.log(object.fcttext);
     alert(object.fcttext);
});

这将循环显示 forecastday 对象并告诉您 fcttext 的值。

由于代码而使用$,ajax;,您可以使用Array.forEachfor

  

链接

     

http://api.jquery.com/each - jQuery.each文档

     

https://developer.mozilla.org - Array.forEach文档

     

https://developer.mozilla.org - for文档