2016-03-05 28 views
0

我有困难的时间遍历这个数据集从ajax调用拉到天气api。我想获取诸如temp或id之类的东西的值,但不断收到错误。我试过这个weather.weather ['id'],weather.weather.id,weather.weather [0]。我知道最高的天气层是一个物体。但第二个天气传递数组?那有一个对象?我如何从这里获取信息?对于正常的数据集我有一些想法,但这对我来说太奇怪了。注:这是VUEJSAjax数据对象意外行为

AJAX调用:

$.getJSON('http://api.openweathermap.org/data/2.5/weather?id=6356055&appid=44db6a862fba0b067b1930da0d769e98', function(weather) { 
       this.weather_data = weather; 
      }.bind(this)); 

这是穿我的数据推到我的空数组

weather_data: [], 

那么现在我只是在努力确保其内的一些工作这样的标签:

{{ weather_data.weather[0].id | json}} 

这里是从getjson调用中拉回来的东西。

 "weather": { 
     "coord": { 
      "lon": 2.13, 
      "lat": 41.4 
     }, 
     "weather": [ 
      { 
       "id": 800, 
       "main": "Clear", 
       "description": "clear sky", 
       "icon": "01d" 
      } 
     ], 
     "base": "cmc stations", 
     "main": { 
      "temp": 285.622, 
      "pressure": 1006.71, 
      "humidity": 98, 
      "temp_min": 285.622, 
      "temp_max": 285.622, 
      "sea_level": 1015.25, 
      "grnd_level": 1006.71 
     }, 
     "wind": { 
      "speed": 2.61, 
      "deg": 267.501 
     }, 
     "clouds": { 
      "all": 0 
     }, 
     "dt": 1457178093, 
     "sys": { 
      "message": 0.0042, 
      "country": "ES", 
      "sunrise": 1457158704, 
      "sunset": 1457200063 
     }, 
     "id": 6356055, 
     "name": "Barcelona", 
     "cod": 200 
    }, 

尝试这种weather_data.weather yeilds这个

  [ 
    { 
    "id": 801, 
    "main": "Clouds", 
    "description": "few clouds", 
    "icon": "02d" 
    } 
] 
+0

https://jsfiddle.net/mca27kfr/ – Rayon

+0

data.weather.weather [0] .id将提供结果。向我们展示如何解析和访问数据。 – Aravind

+0

我添加了更多详细信息 –

回答

0

首先,这种类型的问题我建议你使用的console.log(your_variable),并期待在浏览器的控制台(在Chrome F12)你真的有什么。否则,如果您的原始api响应存储在名为“data”的变量中,data.weather.weather [0] .id应该可以工作。

+0

检查编辑。我添加了更多的细节。我认为这也会起作用,但vuejs的行为很怪异 –

+0

@RickiMoore,你将weather_data定义为数组。但是从你的API你会得到一个对象。可能你想要做的是:this.weather_data = weather.weather。然后稍后,您会执行this.weather_data [0] .id以获取该ID。 – amberv

+0

我试过了,它给了我calendar_component.js:1385Uncaught TypeError:无法读取属性'id'的undefined –