JSON data to int and float

I have the following parsed JSON data :

      Serial.print("JSON object = ");
      Serial.println(myObject);
      Serial.print("Temperature: ");
      Serial.println(myObject["main"]["temp"]);
      Serial.print("Pressure: ");
      Serial.println(myObject["main"]["pressure"]);
      Serial.print("Humidity: ");
      Serial.println(myObject["main"]["humidity"]);
      Serial.print("Wind Speed: ");
      Serial.println(myObject["wind"]["speed"]);

This is basically a readout from the Openweathermap.org site grabbed by a Node MCU ESP8266.

I now want to convert the Temperature data into a float and the Humidity data into a int.

I tried some methods like myObject.getInt(["main"]["temp"]); Of course the IDE got very angry with me for that.

So how to get this done ?

Thanks

1 Like

How about:

myObject(["main"]["temp"]).toInt();

wildbill:
How about:

myObject(["main"]["temp"]).toInt();

No... I got an error saying the 'class JsonVar' has no member 'toInt()'. To help you get a full picture I am posting the loop() function :

void loop() {
  // Send an HTTP GET request
  if ((millis() - lastTime) > timerDelay) {
    // Check WiFi connection status
    if (WiFi.status() == WL_CONNECTED) {
      String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric," + countryCode + "&APPID=" + openWeatherMapApiKey;

      jsonBuffer = httpGETRequest(serverPath.c_str());
      Serial.println(jsonBuffer);
      JSONVar myObject = JSON.parse(jsonBuffer);

      // JSON.typeof(jsonVar) can be used to get the type of the var
      if (JSON.typeof(myObject) == "undefined") {
        Serial.println("Parsing input failed!");
        return;
      }

      Serial.print("JSON object = ");
      Serial.println(myObject);
      Serial.print("Temperature: ");
      Serial.println(myObject["main"]["temp"]);
      Serial.print("Pressure: ");
      Serial.println(myObject["main"]["pressure"]);
      Serial.print("Humidity: ");
      Serial.println(myObject["main"]["humidity"]);
      Serial.print("Wind Speed: ");
      Serial.println(myObject["wind"]["speed"]);

      tempDegC = myObject(["main"]["temp"]).toInt(); 
      humidPercent = myObject(["main"]["humidity"]).toInt(); 

      tempDegC -= 273; 

      Serial.println(tempDegC); 
      Serial.println(humidPercent); 

      ThingSpeak.setField(1, 35);     // Posting dummy values till issue is resolved..
      ThingSpeak.setField(2, 68);
      ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); // Write the fields that you've set all at once.
      
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }

  blinkLED( flashLED, 1000, 1000);
}

I'll guess that this is printing a String object

      Serial.println(myObject["main"]["temp"]);

So what you need is:

      myObject["main"]["temp"].toInt();

wildbill:
I'll guess that this is printing a String object

      Serial.println(myObject["main"]["temp"]);

So what you need is:

      myObject["main"]["temp"].toInt();

Still even with this change it returns the same error 'class JSONVar' has no member named 'toInt'

tempDegC = int(myObject["main"]["temp"]); 
     humidPercent = int(myObject["main"]["humidity"]);

This worked !!

Only now I need to figure how to display the temperature as a double or float with one digit precision ?

Which library are you using for JSON?

wildbill:
Which library are you using for JSON?

This one !

Arduino_JSON

The examples that come with the library suggest that you can just cast to double as you did for int:

  Serial.println((double) myDouble, 4); // prints: 4242.4242

Depending on which Arduino you have, double may be synonymous with float.

wildbill:
The examples that come with the library suggest that you can just cast to double as you did for int:

  Serial.println((double) myDouble, 4); // prints: 4242.4242

Depending on which Arduino you have, double may be synonymous with float.

Yes i first tried to cast to a float and the compiler threw up an error. Next I tried a cast to double and it shut up !!

Now I am posting 2 precision double to the cloud.

Thanks !!

Continuing the discussion from JSON data to int and float:

This is the solution here as well:
String jsonString = JSON.stringify(myObject["main"]["temp"]);

Thanks so much! I've been trying to accomplish this for a few days (trying to use temperature data from Open Weather to determine color of an RGB led with a NodeMCU ESP32); unfortunately, when I use this approach, I keep getting this compiling error: 'tempDegC' was not declared in this scope

I'm very much a newbie, so perhaps I'm forgetting something obvious here. I did declare the tempDegC int variable in the setup. I append below my code (mostly from ESP32 HTTP GET with Arduino IDE (OpenWeatherMap.org and ThingSpeak) | Random Nerd Tutorials), and apologize for its messiness/the way I might have butchered the original excellent code. . .and the likely very basic nature of my question. Thank you in advance!

Code:

/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-open-weather-map-thingspeak-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

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

#define PIN_RED    23 // GIOP23
#define PIN_GREEN  22 // GIOP22
#define PIN_BLUE   21 // GIOP21

const char* ssid = "hidden";
const char* password = "hidden";

// Your Domain name with URL path or IP address with path
String openWeatherMapApiKey = "hidden";
// Example:
//String openWeatherMapApiKey = " ";

// Replace with your country code and city
String city = "Phoenix";
String countryCode = "US";

// THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES
// For a final application, check the API call limits per hour/minute to avoid getting blocked/banned
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 10 seconds (10000)
unsigned long timerDelay = 10000;

String jsonBuffer;

void setup() {
  int tempDegC;
  Serial.begin(115200);
 
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
  
 
  Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading.");

  pinMode(PIN_RED,   OUTPUT);
  pinMode(PIN_GREEN, OUTPUT);
  pinMode(PIN_BLUE,  OUTPUT);
}

void loop() {
   analogWrite(PIN_RED,   120);
   analogWrite(PIN_GREEN, 60);
   analogWrite(PIN_BLUE,  60);
  // Send an HTTP GET request
  if ((millis() - lastTime) > timerDelay) {
    // Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + countryCode + "&APPID=" + openWeatherMapApiKey;
      
      jsonBuffer = httpGETRequest(serverPath.c_str());
      Serial.println(jsonBuffer);
      JSONVar myObject = JSON.parse(jsonBuffer);
  
      // JSON.typeof(jsonVar) can be used to get the type of the var
      if (JSON.typeof(myObject) == "undefined") {
        Serial.println("Parsing input failed!");
        return;
      }
    
      Serial.print("JSON object = ");
      Serial.println(myObject);
      Serial.print("Temperature: ");
      Serial.println(myObject["main"]["temp"]);
      Serial.print("Pressure: ");
      Serial.println(myObject["main"]["pressure"]);
      Serial.print("Humidity: ");
      Serial.println(myObject["main"]["humidity"]);
      Serial.print("Wind Speed: ");
      Serial.println(myObject["wind"]["speed"]);      
      tempDegC = int(myObject["main"]["temp"]);  
      
                }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }

  
  if (tempeDegC) > 273   {
   analogWrite(PIN_RED,   20);
   analogWrite(PIN_GREEN, 250);
   analogWrite(PIN_BLUE,  0);
  }

  
}

String httpGETRequest(const char* serverName) {
  WiFiClient client;
  HTTPClient http;
    
  // Your Domain name with URL path or IP address with path
  http.begin(client, serverName);
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  
  String payload = "{}"; 
  
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

and here are the compiler error messages:

C:\Users\Desktop\Arduino \open_weather_api_test_if_then_sketch\open_weather_api_test_if_then_sketch.ino: In function 'void loop()':
open_weather_api_test_if_then_sketch:95:7: error: 'tempDegC' was not declared in this scope
       tempDegC = int(myObject["main"]["temp"]);
       ^~~~~~~~
C:\Users\Desktop\Arduino\open_weather_api_test_if_then_sketch\open_weather_api_test_if_then_sketch.ino:95:7: note: suggested alternative: 'tempnam'
       tempDegC = int(myObject["main"]["temp"]);
       ^~~~~~~~
       tempnam

Multiple libraries were found for "WiFi.h"
 Used: C:\Users\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.4\libraries\WiFi
 Not used: C:\Program Files (x86)\Arduino\libraries\WiFi
exit status 1
'tempDegC' was not declared in this scope