Search code examples
jsonvue.jsopenweathermapvue-resource

How to modify nested JSON data with Vue and Vue Resource


Working on something very simple in Vue using OpenWeatherMap API.

Can render all the data properly but I want to modify such data and not sure what's the best way to achieve that.

Here's is my code:

index.pug

section#weather
  ul
    li(v-for='forecast in forecasts')
      p.time Time: {{ times }}
      p.temperature Temperature: {{ temperatures }}º
      p.description Description: {{ forecast.weather[0].description }}
      img.icon(v-bind:src="'https://openweathermap.org/img/w/' + forecast.weather[0].icon + '.png'")

script.js

var weather = new Vue({
el: '#weather',

data: {
    forecasts: [],
    temperatures: [],
    times: []
},

created: function () {
    this.fetchData();
},        

methods: {
    fetchData: function () {
                     this.$http.get('http://api.openweathermap.org/data/2.5/forecast?q=london&units=metric&appid=YOURAPIKEY')
        .then(response => {
            this.forecasts = response.data.list;
            this.temperatures = Math.round(response.data.list[0].main.temp);
            this.times = moment.unix(response.data.list[0].dt);
        })
    }
}
});

This will render just the first time and temperature, but the correct various descriptions and icons.

Changin stuff in index.pug to p.time Time: {{ forecast.dt }} for example works fine but can't then modify the time format.

More information on how the OpenWeatherMap JSON is formatted here: https://openweathermap.org/forecast5


Solution

  • You shouldn't hardcode the 0-index when parsing your data (and setting it to this.temperatures and this.times). Instead, since forecast is the same as forecasts[i] at any cycle of the loop, do:

    section#weather
      ul
        li(v-for='forecast in forecasts')
          p.time Time: {{ forecast.dt}}
          p.temperature Temperature: {{ Math.round(forecast.main.temp) }}º
          p.description Description: {{ forecast.weather[0].description }}
          img.icon(v-bind:src="'https://openweathermap.org/img/w/' + forecast.weather[0].icon + '.png'")
    

    And your fetchData() becomes simply:

    fetchData: function () {                    
      this.$http.get('http://api.openweathermap.org/data/2.5/forecast?q=london&units=metric&appid=YOURAPIKEY')
        .then(response => this.forecasts = response.data.list)
    }