I have worked with openweathermap before and displaying weather data has worked very well.
I've now tried to use the same code to fetch weather data from a German API (Deutscher Wetterdienst "DWD"). But the JSON structure is a little different so I cannot display the data with my code. I don't understand the error text displayed in the terminal. It says "Parsing error: Unexpected token, expected "}".
First of all here is a the JSON structure from the API:
{
"10384": {
"forecast1": {
"stationId": "10384",
"start": 1664834400000,
"timeStep": 3600000,
"temperature": [],
"temperatureStd": [],
"windSpeed": null,
"windDirection": null,
"windGust": null,
"icon": [
],
"precipitationTotal": [],
"precipitationProbablity": null,
"precipitationProbablityIndex": null
},
"forecastStart": null,
"days": [
{
"stationId": null,
"dayDate": "2022-10-04",
"temperatureMin": 93,
"temperatureMax": 157,
"icon": 3,
"icon1": null,
"icon2": null,
"precipitation": 0,
"windSpeed": 111,
"windGust": 296,
"windDirection": 2740,
"sunshine": 1920
}
],
}
The number "10384" at the top is the ID of the weather station. After fetching the API, I store the json object into a state variable called "data".
Then I want to display "10384"-> "forecast1" -> "temperature" and "10384" -> "days" -> "temperatureMin".
But I can't because of the "10384" being an integer.
My full code:
useEffect(() => {
const getData = async () => {
try {
const response = await
fetch('https://dwd.api.proxy.bund.dev/v30/stationOverviewExtended?stationIds=433,10384'
,{
method: "GET",
mode: "cors",
headers: {"content-type": "application/json" }
}
)
if (!response.ok) {
throw new Error(
`HTTP error. Status: ${response.status}`
);
}
let actualData = await response.json();
setData(actualData);
console.log(actualData);
setError(null);
} catch(err) {
setError(err.message);
setData(null);
} finally {
setLoading(false);
}
}
getData()
}, [])
return (
<div>
{loading && <div>Loading...</div>}
{error && (
<div>{`Fehler beim Fetchen von Daten. Error fetching data - ${error}`}</div>
)}
<div className="widget-container">
{/* Temepraturausgabe Wetter-Icon*/}
<div className="temp-container">
<span className="tempNow">{data.10384? <h1>{data.10384.days}: null}</span>
</div>
</div>
</div>
);
}
Somehow I cannot map over the "10384" so I can't access the nested data.
The weather station ID right at the beginning is the problem. Are numbers not allowed? how can I access the nested data?
Thank you
CodePudding user response:
Have your span as below:
<span className="tempNow">
{(data && data["10384"]) ? <h1>data["10384"]?.days[0]?.temperatureMin </h1> : null}
</span>;
as the object keys are always strings you can access by notation []
..