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
undefinedis not a valid latitude right? Both lat and lon coming from your data structure areundefined. I would work on fixing that first.FetchError: request...clearly states both lat and lon areundefined. Unless there is a different error message that you are attempting to fix than the one you provided above, it is indisputable.const base = ...assignment is where this happens. If youconsole.log(lat, long)just before that statement, you will see they areundefinedthere. That implies you're not parsing your data correctly. Fix that.