How to extract a JSON value using Arduino_JSON.h?

I get a JSON object from OpenWeatherMap.org like this:

{
  "coord": {
    "lon": -100.00,
    "lat": 50.00
  },
  "weather": [
    {
      "id": 804,
      "main": "Clouds",
      "description": "overcast clouds",
      "icon": "04d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 45.63,
    "feels_like": 45.63,
    "temp_min": 44.02,
    "temp_max": 47.41,
    "pressure": 1012,
    "humidity": 93,
    "sea_level": 1012,
    "grnd_level": 1004
  },
  "visibility": 8929,
  "wind": {
    "speed": 1.99,
    "deg": 0,
    "gust": 5.99
  },
  "clouds": {
    "all": 100
  },
  "dt": 1730408,
  "sys": {
    "type": 2,
    "id": 200851,
    "country": "US",
    "sunrise": 17302309,
    "sunset": 17306539
  },
  "timezone": -2800,
  "id": 5000000,
  "name": "City",
  "cod": 200
}

reading out ["main"]["temp"] works correctly like this:

Serial.println(weatherObject["main"]["temp"]);
Serial.println(weatherObject["weather"]["id"]);
Serial.println(weatherObject["weather"]["description"]);

But id and description fail. The printed values are:
45.63
null
null

How do I get at ["weather"]["description"] and ["weather"]["id"]?

"Weather" is not a record, like "main". It's an array of records. You need to specify which one you want to read.

In JSON, braces { ... } group together the attributes in a record. But square brackets [ ... ] indicate a list or array.

Good I see that now.
I tried this syntax but it still isn't correct:

Serial.println(weatherObject["weather"][0]["description"]);

Another hint?

Try

Serial.println(weatherObject["weather"][0]["id"]);

It still prints null

Hmm...

Oh wait! I think it is working now! I needed to clear the serial monitor. Yes I get the values now. Thank you!

1 Like