JSON deserialize

First time working with this JSON library. I don't understand how to reference humidity or wind_mph. temp_f is working.

deserializeJson(doc, jsonline);

tempM = doc["current"]["temp_f"];
humiM = doc["humidity"];
wind_speed = doc["wind_mph"];

{
  "location": {
    "name": "City",
    "region": "State",
    "country": "USA",
    "lat": 33.02,
    "lon": -80.21,
    "tz_id": "America/New_York",
    "localtime_epoch": 1714070832,
    "localtime": "2024-04-25 14:47"
  },
  "current": {
    "temp_c": 26.6,
    "temp_f": 79.9,
    "is_day": 1,
    "condition": {
      "text": "Sunny",
      "icon": "//cdn.weatherapi.com/weather/64x64/day/113.png",
      "code": 1000
    },
    "wind_mph": 4.3,
    "wind_kph": 6.8,
    "wind_degree": 3,
    "wind_dir": "N",
    "humidity": 34,
    "cloud": 21
  }

I think you're missing a closing parens after code:1000
if not then humidity is under "current" .

I don't get it but it works as you said, I referenced them as current and I get the data. But they are not in the current set. The brace is there for "code": 1000, it's on the next line, I used the 'pretty-print' in Chrome to make it more readable for the post.

This works:
tempM = doc["current"]["temp_f"];
humiM = doc["current"]["humidity"];
wind_speed = doc["current"]["wind_mph"];

They are in the "current" set because you need another closing parens after code:1000
You need two there because you need to close "condition" then close "current".
Take a look.

You can use this site to check your json:

Copy your json and paste at text area.
After click viewer

Wow you are right, I went back to the serial console and when I copied the string (Ctrl-C) I missed the last brace! Thanks, I never would have figured that one out.

On the web there are a bunch of websites that can test your json and you can run querys against it .
That's how I learned it. I just copied you json into one of those sites and got an error. Then I could see you left out a closing brace.

Good luck

Dear, with a similar problem with the JSON library. I am a fan of these topics and I am doing a project that needs to have climate data from a website.
I based the program on another one I found on YouTube.
Apparently the JSON data is taken correctly and displayed well in the print via print monitor but there would be an error since error.c_str()) gives the error EmptyInput and when I print to the monitor the data gives all 0, zero despite the fact that in the JSON string they have corresponding values.
For example, the value of Temperature = 285.84 in the JSON string but when printed it is 0.00. Or perhaps there is an error in the handling of variables?

I hope I was clear.

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

String payload;

// Reemplace con la información de su red WiFi
const char* ssid = "xxxxxxxx";
const char* password = "xnxnxnxnx";

// Reemplace con la información de la API del clima
const char* apiUrl = "https://api.openweathermap.org/data/2.5/weather?lat=-34.66&lon=-58.37&appid=7d7fr777676s1xc555e5eldowwmsod";

void setup() {
  Serial.begin(115200);

  // Conectarse a WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi conectado");

  // Obtener datos del clima
  getDataWeather();
}

void loop() {
  delay(10000); // Actualizar cada 10 segundos
  getDataWeather();
}

void getDataWeather() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    // Make the HTTP GET request
    http.begin(apiUrl);
    int httpCode = http.GET();

    if (httpCode > 0) {
      // Check if the request was successful
      if (httpCode == HTTP_CODE_OK) { 
        String payload = http.getString();
        Serial.println("JSON Received:");
        Serial.println(payload);
      } 
        // Parse the JSON
        JsonDocument doc; // Declare the 'doc' variable
        DeserializationError error = deserializeJson(doc, payload);

        Serial.println(error.c_str());
        Serial.println(httpCode);
                
        float coord_lon = doc["coord"]["lon"]; // -58.37
        float coord_lat = doc["coord"]["lat"]; // -34.66

        JsonObject weather_0 = doc["weather"][0];
        int weather_0_id = weather_0["id"]; // 800
        const char* weather_0_main = weather_0["main"]; // "Clear"
        const char* weather_0_description = weather_0["description"]; // "clear sky"
        const char* weather_0_icon = weather_0["icon"]; // "01d"
       
        const char* base = doc["base"]; // "stations"

        JsonObject main = doc["main"];
        float main_temp = main["temp"]; // 286.59
        // main_temp = main_temp - 273.15; // Conversion a °C
        // char temp[7];
        // snprintf(temp, 7, "%f", main_temp);
        Serial.print("Temperatura: ");
        Serial.print(main_temp);
        Serial.println(" °C");
                           
        float main_feels_like = main["feels_like"]; // 285.14
        float main_temp_min = main["temp_min"]; // 285.2
        float main_temp_max = main["temp_max"]; // 287.78
        int main_pressure = main["pressure"]; // 1021
        int main_humidity = main["humidity"]; // 44
        int visibility = doc["visibility"]; // 10000

        JsonObject wind = doc["wind"];
        float wind_speed = wind["speed"]; // 12.07
        int wind_deg = wind["deg"]; // 270
        float wind_gust = wind["gust"]; // 15.2

        int clouds_all = doc["clouds"]["all"]; // 0
        long dt = doc["dt"]; // 1715264467

        JsonObject sys = doc["sys"];
        int sys_type = sys["type"]; // 2
        long sys_id = sys["id"]; // 2008409
        const char* sys_country = sys["country"]; // "AR"
        long sys_sunrise = sys["sunrise"]; // 1715250961
        long sys_sunset = sys["sunset"]; // 1715288630

        int timezone = doc["timezone"]; // -10800
        long id = doc["id"]; // 7535637
        const char* name = doc["name"]; // "Avellaneda"
        int cod = doc["cod"]; // 200
          
          } else {
      Serial.println("Error fetching weather data: HTTP code");
      Serial.println(httpCode);
    }
    http.end();   // Release resources
  } else {
    Serial.println("WiFi not connected");
  }
}

Print Monitor Output

I noticed you are using the 2.5 API call from OpenWeatherMap. That call is going away next month (June 2024). You have to start using the 3.0 API which requires that your account be setup with a credit card.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.