Home > Net >  How can I take a value from a JSON file to a const?
How can I take a value from a JSON file to a const?

Time:09-29

I'm currently working on a project where I need to take the data from a JSON file to use that data in a fetch of an API (this works), the data I need to take from de JSON file are latjson and lonjson and both put them into const lat: info.latjson and const lon: info.latjson I tried this and my error is Uncaught (in promise) TypeError: Cannot read property 'lat' of undefined (in the line of "const: base....")

Heres is my JSON file:

[
    {   
        "latjson": 21.1524,
        "lonjson": -101.7108
    },
    {
        "latjson": 21.1447,
        "lonjson":-101.6852
    }, 
    {
        "latjson": 21.1155,
        "lonjson": -101.6575
    }
]

and here is my script

function calcWeather(){ 
    let info  = ''

    fetch('../js/data.json') // fetch editable c:
    .then(function(response) {
        return response.json();
     })
    .then(function(myJson) {
        info = myJson
        console.log(info)
    });
     

    const lat = info.latjson;
    const long = info.lonjson;

    const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
}

CodePudding user response:

Fetch runs asynchronously, so when you access "info.latjson" it is not guaranteed that the the fetch has already run and assigned the result JSON to your "info" object.

Either move the code below your fetch into the second callback or use async await:

async function calcWeather(){ 
    const response = await fetch('../js/data.json');
    const info = await response.json();     

    const lat = info.latjson;
    const long = info.lonjson;

    const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
}

CodePudding user response:

You need to store values of lat and lon in arrays.

const lat = info.map((obj) => { return obj.latjson; });

const lon = info.map((obj) => { return obj.lonjson; });

CodePudding user response:

You have 2 mistake,

  1. You read the value outside asynchronous process
  2. You read the value an array, not object

Might this can help you

async function calcWeather(){ 

  const info = await fetch('../js/data.json') // fetch editable c:
  .then(function(response) {
      return response.json();
   });
 
  // Here's is simple way to access index 0
  const lat = info[0].latjson;
  const long = info[0].lonjson;

  const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
}
  • Related