arduino-libraries / Arduino_JSON

Official JSON Library for Arduino
GNU Lesser General Public License v2.1
151 stars 60 forks source link

how to parse [] empty JSON elements #8

Closed MHz000 closed 3 years ago

MHz000 commented 4 years ago

I'm struggeling parsing a JASON-object received by OpenWeatherMap like this one:

{"coord":{"lon":9.18,"lat":47.66},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"base":"stations","main":{"temp":284.22,"feels_like":282.44,"temp_min":283.15,"temp_max":284.82,"pressure":1013,"humidity":93},"visibility":10000,"wind":{"speed":2.6,"deg":50},"clouds":{"all":91},"dt":1591596373,"sys":{"type":1,"id":1310,"country":"DE","sunrise":1591586764,"sunset":1591643939},"timezone":7200,"id":2885679,"name":"Konstanz","cod":200}

Access induvidual values I use code like this:

float fTemp = obj["main"]["temp"].as<float>() -273.15;    with success

However the weather element:

"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],

is encapsulated in additional [...] How can I access values for "id", "main", etc? in arduino/c++ idiom?

Trying:

  int id = obj["weather"]["0"]["id"].as<int>();                           
  String situation = obj["weather"]["0"]["main"].as<String>();  
  ...

compiles fine but give "0" or "null" as result

Thanl you for any advice

MHz000 commented 4 years ago

Thank you for fast replay Benoit! You're absolutely right😊 Sorry for my delayed answer. There was an internet access blackout. Curious in this situation I get an "Error compiling source". I love arduino IDE🤔

All the best MHz000

Am Mo., 8. Juni 2020 um 09:19 Uhr schrieb Benoît Blanchon < notifications@github.com>:

Hi @MHz000 https://github.com/MHz000

Please try:

int id = obj["weather"][0]["id"]; String situation = obj["weather"][0]["main"];

The result could still be null if deserializeJson() https://arduinojson.org/v6/api/json/deserializejson/ fails.

See also:

Best regards, Benoit

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/arduino-libraries/Arduino_JSON/issues/8#issuecomment-640416341, or unsubscribe https://github.com/notifications/unsubscribe-auth/AB42SGTTAI4B7N5KVDD5KRLRVSGJ3ANCNFSM4NYBJYYQ .

ngxquanganh commented 3 years ago

i got the same error and can't see reply of Benoit, how can you solve this