Home > other >  How to get info from a JSON?
How to get info from a JSON?

Time:10-11

I'm new around here and I'm studying JS! In particular JSON! However, I have come across an exercise that I cannot solve, also because I do not understand what I am doing wrong. I need to extract the information about the planets from the StarWars API. So I do the classic fetch and as a result I get the generic information about the planet in the form of a JSON. However, I have to extract the planet name and I get stuck, because when I check the PlanetsData variable, it gives me undefined. Ergo the cycle I wrote to extract the names of the planets doesn't work for some reason. So, my question is:

  1. Why do I get "undefined" for the PlanetsData variable? .. Shouldn't I get the JSON, which displays correctly in the console?
  2. Did I write the cycle correctly? Thanks to who will answer me!

This is my code:

async function getPlanetsData() {
  const planetsData = await fetch ("https://swapi.dev/api/planets").then(data => {
    return data.json()}).then(planets => {console.log(planets.results)}) //  ---> Here i receive the JSON data
    for (let key in planetsData) {
      const someInfo = planetsData.results[key].name
      console.log(JSON.stringify(someInfo)) } //  ---> I don't understand why, but I don't get anything here. There is no response in the console, as if the call did not exist
}   
getPlanetsData()

CodePudding user response:

You can write the same function in a different and clearer way, check the comments to understand the code!

async function getPlanetsData() {
    
    // 1. Fetch and wait for the response
    const response = await fetch ("https://swapi.dev/api/planets");

    // 2. Handle the response, in that case we return a JSON
    //    the variable planetsData now have the whole response
    const planetsData = await response.json();

    // console.log(planetsData); // this will print the whole object

    // 3. Return the actual data to the callback
    return planetsData;
}

// Function usage 
// 4. Call "getPlantesData" function, when it completes we can call ".then()" handler with the "planetsData" that contains your information
getPlanetsData().then(planetsData => {
    // 5. Do whatever you want with your JSON object
    //    in that case I choose to print every planet name
    var results = planetsData.results; // result array of the object
    results.forEach(result => console.log(result.name));
});

CodePudding user response:

It seems that you have the same issue as : read and save file content into a global variable

Tell us if it does solve your issue or not.

(UPDATE)

To answer explicitly to your questions.

  1. First question:

To get value into variable planetsData you have only one option

async function getPlanetsData() {
  const response = await fetch ("https://swapi.dev/api/planets")
  const planetsData = await response.json()
  for (let key in planetsData) {
    const someInfo = planetsData.results[key].name
    console.log(JSON.stringify(someInfo))
  }
}   
getPlanetsData()

A second option is possible but not intuitive. planetsData will have value only when the fetch is done. Your for loop will be performed before your fetch is done, and so before planetsData gets a value

function getPlanetsData() {
  let planetsData;
  fetch("https://swapi.dev/api/planets")
    .then((data) => {
      return data.json();
    })
    .then((planets) => {
      planetsData = planets;
    });

  for (let key in planetsData) { // /!\ planetsData can be undefined
    const someInfo = planetsData.results[key].name
    console.log(JSON.stringify(someInfo))
  }

}
getPlanetsData();
  1. Second question:

You didn't write the cycle correctly. To resolve promises it is preferable to choose between using await and.

  • Related