简体   繁体   中英

We need to go deeper - Deep accessing JSON & array with foreach loop in Vanilla Javascript

Not absolutely new to Java Script but still a novice in some aspects, including accessing JSON objects and arrays. I tried different syntax and options with []array accessing, however failed.

I would like to access the JSON file at this location.

{
  "coord": {
    "lon": -0.13,
    "lat": 51.51
  },
  "weather": [{
    "id": 521,
    "main": "Rain",
    "description": "shower rain",
    "icon": "09d"
  }],
  "base": "stations",
  "main": {
    "temp": 289.89,
    "pressure": 1002,
    "humidity": 87,
    "temp_min": 288.15,
    "temp_max": 291.48
  },
  "visibility": 10000,
  "wind": {
    "speed": 5.1,
    "deg": 210,
    "gust": 10.8
  },
  "rain": {
    "1h": 0.25
  },
  "clouds": {
    "all": 40
  },
  "dt": 1569596940,
  "sys": {
    "type": 1,
    "id": 1414,
    "message": 0.012,
    "country": "GB",
    "sunrise": 1569563635,
    "sunset": 1569606559
  },
  "timezone": 3600,
  "id": 2643743,
  "name": "London",
  "cod": 200
}

Using a foreach loop to access the data, I am not quite sure how the proper syntax would be for this.

Ultimately, I would just want to achieve the following with string literals:

Display in HTML:

City ID
City Weather Description
City Name

See code:

// weather api definition
let url = 'http://api.openweathermap.org/data/2.5/weather?q=London&APPID=7b67b3fc2a0559b8301bd032e8f2f1c7'
let weatherInfo = document.getElementById('title');

fetch(url).then(function (response) {
  return response.json();
})
.then(function(data) {
  document.getElementById('weather-info').innerHTML = '<h2 id="title"></h2>';
  document.getElementById('title').innerHTML = 'THIS IS JASOOON';
  //here is where my problems start
  let output = '<h4>Weather Info - cities</h4>';
  data.foreach((item)=> {
    console.log(item.weather)
  });

  data.foreach(function(item) {
    output += `
  <ul>
    <li> City ID: ${item.id} </li>
    <li> City Weather Description: ${item.description} </li>
    <li> City Name ${item.name} </li>
  </ul>`;

  document.getElementById('weather-info').innerHTML = output;
  });

})
.catch(err => {
  console.log('errorMessage');
});

Not sure what all the looping is about since it is returning one city.

 // weather api definition let url = 'http://api.openweathermap.org/data/2.5/weather?q=London&APPID=7b67b3fc2a0559b8301bd032e8f2f1c7' let weatherInfo = document.getElementById('title'); fetch(url).then(function(response) { return response.json(); }).then(function(data) { const weather = data.weather.map(report => report.description).join(", ") let output = ` <h4>Weather Info - cities</h4> <ul> <li> City ID: ${data.id} </li> <li> City Weather Description: ${weather} </li> <li> City Name ${data.name} </li> </ul>`; document.getElementById('weather-info').innerHTML = output; }).catch(err => { console.log('errorMessage'); });
 <div id="weather-info"></div>

Since the Weather property is an Array , you can iterate over it.

 let url = 'http://api.openweathermap.org/data/2.5/weather?q=London&APPID=7b67b3fc2a0559b8301bd032e8f2f1c7' fetch(url).then(function (response) { return response.json(); }).then(function (data) { let output = '<h4>Weather Info - cities</h4>'; // access the weather property and loop through it data.weather.forEach(function (item) { // log the Stringfied version console.log(JSON.stringify(item)); output += ` <ul> <li> City ID: ${item.id} </li> <li> City Weather Description: ${item.description} </li> <li> City Name ${data.name} </li> </ul> <br>`; document.getElementById('weather-info').innerHTML = output; }); }).catch(err => { console.log(err.message); console.log('errorMessage'); });
 <div id="weather-info"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM