Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

282
Visualizações
How can I add data from a JSON to a constant variable in Node JS?

I'm working in a NodeJS. I want to take data from data.json, a JSON file with with coords (lat and lon) and use them to bring up the weather and other stuff, using the Open Weather API. I'm expecting to bring that coords from the JSON and then create the objects but I get my data as undefined:

Official Id: undefined
https://api.openweathermap.org/data/2.5/onecall?lat=undefined&lon=undefined&exclude=hourly,daily&appid=123

Here's a little example of the data.json:

[
  {
    "latjson": 1,
    "lonjson": 1,
    "IdOficina": "1"
  },
  {
    "latjson": 2,
    "lonjson": 2,
    "IdOficina": "2"
  }
]

and here is how I'm trying to save that data in a const

function calcWeather1() {
    var data = fs.readFileSync("./json/data.json", "utf8");
    /*const data = [{
        "latjson": "33.44",
        "lonjson": "-94.04",
        "IdOficina": "1"
    },
    {
        "latjson": 2,
        "lonjson": 2,
        "IdOficina": "2"
    }
    ];*/

    for (let item of data) {
        let url = `https://api.openweathermap.org/data/2.5/onecall?lat=${item.latjson}&lon=${item.lonjson}&exclude=hourly,daily&appid=123`;

        console.log(`Official Id: ${item.IdOficina}`);
        console.log(url);
        console.log('-----------');
    }
}

The issue is that, when I send the JSON data like Randy told me:

/*const data = [{
        "latjson": "33.44",

I get:

Official Id: 1
https://api.openweathermap.org/data/2.5/onecall?lat=33.44&lon=-94.04&exclude=hourly,daily&appid=123

it works, but when I take it from a JSON file, like:

var data = fs.readFileSync("./json/data.json", "utf8");

I get

Official Id: undefined
https://api.openweathermap.org/data/2.5/onecall?lat=undefined&lon=undefined&exclude=hourly,daily&appid=123
-----------

EDIT: I tried bringing data as Randy told me:

const json = fs.readFileSync("./json/data.json", "utf8");
const data = JSON.parse(json);
for (let item of data) {...

and still getting undefined

EDIT: Here's my data.json, I added the way it is structured here but here is the file

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

EDIT: OP is has not parsed the JSON string from the file, adding those instructions. When reading the file, you read it in as a string, it must be parsed into a JavaScript Object. Use JSON.parse() to accomplish that goal.

const json = fs.readFileSync("./json/data.json", "utf8");
const data = JSON.parse(json);

Now the data variable contains the array of objects. If you look at the first array element and ask for its jsonlat it should return the correct data:

data[0].latjson

Now you are ready to continue with the below instructions:

You are not parsing the array properly. Given the comments and the change to the data structure discussed there, this is the data to parse:

[
  {
    "latjson": 1,
    "lonjson": 1,
    "IdOficina": "1"
  },
  {
    "latjson": 2,
    "lonjson": 2,
    "IdOficina": "2"
  }
]

Rather than use for...in you should really use for...of it will make it easier and will keep you out of trouble down the road with other coding you do.

Here is what that would look like:

const fakeAPIKey = 12342456478;
const data = [{
    "latjson": "33.44",
    "lonjson": "-94.04",
    "IdOficina": "1"
  },
  {
    "latjson": 2,
    "lonjson": 2,
    "IdOficina": "2"
  }
];


for (let item of data) {
  let url = `https://api.openweathermap.org/data/2.5/onecall?lat=${item.latjson}&lon=${item.lonjson}&exclude=hourly,daily&appid=${fakeAPIKey}`;

  console.log(`Official Id: ${item.IdOficina}`);
  console.log(url);
  console.log('-----------');
}

about 4 years ago · Juan Pablo Isaza Relatório

0

{"cod":"400","message":"wrong latitude"} you are getting bad request response from the API. It appears from the error message that the latitude is wrong

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda