我有以下json对象,我想显示天气对象描述,当我尝试显示它给出undefined的对象时。任何人都可以告诉我如何访问它?
{
"coord": {
"lon": 80.28,
"lat": 13.09
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 299.15,
"pressure": 1015,
"humidity": 74,
"temp_min": 299.15,
"temp_max": 299.15
},
"visibility": 6000,
"wind": {
"speed": 3.1,
"deg": 60
},
"clouds": {
"all": 0
},
"dt": 1519491600,
"sys": {
"type": 1,
"id": 7834,
"message": 0.0057,
"country": "IN",
"sunrise": 1519433836,
"sunset": 1519476414
},
"id": 1264527,
"name": "Chennai",
"cod": 200
}
答案 0 :(得分:2)
对象weather
是一个数组,因此您需要遍历对象。
您可以使用forEach
功能。
var obj = { "coord": { "lon": 80.28, "lat": 13.09 }, "weather": [{ "id": 800, "main": "Clear", "description": "clear sky", "icon": "01n" }], "base": "stations", "main": { "temp": 299.15, "pressure": 1015, "humidity": 74, "temp_min": 299.15, "temp_max": 299.15 }, "visibility": 6000, "wind": { "speed": 3.1, "deg": 60 }, "clouds": { "all": 0 }, "dt": 1519491600, "sys": { "type": 1, "id": 7834, "message": 0.0057, "country": "IN", "sunrise": 1519433836, "sunset": 1519476414 }, "id": 1264527, "name": "Chennai", "cod": 200};
obj.weather.forEach(w => console.log(w.description));
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
只需访问对象的weather
属性,该属性只是一个项目(item [0])的数组,这是另一个对象,然后是该对象的description
属性:
var obj = {"coord":{"lon":80.28,"lat":13.09},
"weather":[
{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}
],
"base":"stations",
"main":{"temp":299.15,"pressure":1015,"humidity":74,"temp_min":299.15,"temp_max":299.15},
"visibility":6000,
"wind":{"speed":3.1,"deg":60},
"clouds":{"all":0},"dt":1519491600,
"sys":{"type":1,"id":7834,"message":0.0057,"country":"IN","sunrise":1519433836,"sunset":1519476414},
"id":1264527,"name":"Chennai","cod":200
};
console.log(obj.weather[0].description);
如果您对将要返回的JSON有任何控制权,则weather
似乎不需要包含对象的数组。如果总是只有一个对象,那么结构将更有意义:
{"coord":{"lon":80.28,"lat":13.09},
"weather":{"id":800,"main":"Clear","description":"clear sky","icon":"01n"},
...