解析json响应并在div中显示数据。天气api

时间:2016-06-02 09:38:09

标签: javascript jquery html json

如何解析json data.i需要从值 weather.main和weather.description 的json响应中提取数据并在div.i中显示它们已经发布了json响应和js, jquery脚本



//this json response and i need to extract values of  weather.main and weather.description
{  
   "coord":{  
      "lon":80.28,
      "lat":13.09
   },
   "weather":[  
      {  
         "id":802,
         "main":"Clouds",
         "description":"scattered clouds",
         "icon":"03d"
      }
   ],
   "base":"stations",
   "main":{  
      "temp":308.15,
      "pressure":1004,
      "humidity":53,
      "temp_min":308.15,
      "temp_max":308.15
   },
   "visibility":7000,
   "wind":{  
      "speed":3.6,
      "deg":260
   },
   "clouds":{  
      "all":40
   },
   "dt":1464852600,
   "sys":{  
      "type":1,
      "id":7834,
      "message":0.0103,
      "country":"IN",
      "sunrise":1464826282,
      "sunset":1464872558
   },
   "id":1264527,
   "name":"Chennai",
   "cod":200
}






  <script>   
            function loadweather(){
            var q =  document.getElementById("in").value;
            var appid = "086a3e2bd775aac95a9b096b5233f049";
            var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + q + '&appid=' + appid + '&units=metric';
            $.getJSON(url, function (data) { $('.temp').html('' + data.main.temp + '&#176C')});
            alert("parse2");
//how to access this json data "weather->main"
                $.getJSON(url, function (data) { $('.cityname').html('' + data.weather.main)});
            
}
        </script>
&#13;
&#13;
&#13;

如何解析json data.i需要从值 weather.main和weather.description 的json响应中提取数据并在div.i中显示它们已经发布了json响应和js, jquery脚本

1 个答案:

答案 0 :(得分:0)

你可以这样做:

var obj = JSON.parse(Your_json);
obj.weather[0].main // return clouds
obj.weather[0].description // return scattered clouds
$( "body" ).append("<div>"+obj.weather[0].main+"</div>")
$( "body" ).append("<div>"+obj.weather[0].description+"</div>")