Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display nested weather data from a German API (DWD). Numbers in headers a problem?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "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.

Error I get:

The weather station ID right at the beginning is the problem. Are numbers not allowed? how can I access the nested data?

Thank you

>Solution :

Have your span as below:

<span className="tempNow">
  {data["10384"] ? <h1>data["10384"]?.days[0]?.temperatureMin </h1> : null}
</span>;

as the object keys are always strings you can access by notation [] ..

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading