• Post comments:0 Comments
  • Reading time:5 mins read

Unlike other “modern” programming languages like Python or Javascript, there is no built-in JSON parsing function for Embedded C++.

However, JSON is already becoming the industry standard for modern RESTful API data exchange. Like the Smart Living Room project, we presented with ESP8266 and the clarkwise touch screen. We are not only need to get the location according to the IP address but also need to obtain the weather forecast data from the weather data API provider.

Don’t worry, you don’t have to build the wheel, there is a mature and fast library called ArduinoJSON that could do the job.

It only takes a few steps, we will make an example based on getting the current location based on IP address.

So, What is JSON

In case you don’t know that it is actually a lightweight format for storing and transporting data. You can find more details on w3schools.com. It gives a very easy-to-understand key=>value mapping data format. With the help of ArduinoJSON library, it is fairly easy to parse JSON in an embedded system.

Then, what is ArduinoJSON

Quoting: ArduinoJson was created and is maintained by Benoît Blanchon, an experienced C++ developer who, like you, enjoys playing with electronics from time to time.

It is the best JSON library on Arduino in 2021, fast, lightweight, powerful, and easy to use!

Parse a JSON string in Arduino/ESP32/ESP8266 in 4 steps

It is a very common application for ESP8266 or ESP32 when they are trying to get data from a server API. Today we are going to show you how. Only need 4 steps:

1 – Install ArduinoJSON library on Arduino IDE Library Manager

Open Arduino IDE library manager
Open Arduino IDE library manager
Find and install ArduinoJSON on Library Manager
Find and install ArduinoJSON on Library Manager

Before you can use the ArduinoJson library, you have to install it on your Arduino IDE. Click “Sketch > Include Library > Manage Libraries” to run Library Manager.

Inside Library Manager, type “ArduinoJSON” in the searching box. Click the Install button to install.

2 – Obtain JSON data

In this article, we use the service from ip-api.com.It can show your IP location even with latitude and longitude. It is fast and FREE! You don’t even need an API Key.

According to the documentation, if we only need to obtain the latitude and longitude of the current IP address, all we need to do is to GET this URL:

http://ip-api.com/json/?fields=lat,lon

And the returned result like:

{"lat":22.2908,"lon":114.1501}

To perform the HTTP GET request, we made some changes under the official ESP8266 BasicHttpClient demo.

				
					/**
   BasicHTTPClient.ino
    Created on: 24.05.2015
*/

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>

#include <WiFiClient.h>

ESP8266WiFiMulti WiFiMulti;

void setup() {

  Serial.begin(115200);
  // Serial.setDebugOutput(true);

  Serial.println();
  Serial.println();
  Serial.println();

  for (uint8_t t = 4; t > 0; t--) {
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("SSID", "PASSWORD");

}

void loop() {
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED)) {

    WiFiClient client;

    HTTPClient http;

    Serial.print("[HTTP] begin...\n");
    if (http.begin(client, "http://ip-api.com/json/?fields=lat,lon")) {  // HTTP


      Serial.print("[HTTP] GET...\n");
      // start connection and send HTTP header
      int httpCode = http.GET();

      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = http.getString();
          Serial.println(payload);
        }
      } else {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

      http.end();
    } else {
      Serial.printf("[HTTP} Unable to connect\n");
    }
  }

  delay(10000);
}
				
			

Change the SSID and PASSOWRD on line 33 to your actual WIFI situation.

The variable payload on line 60 is the returned JSON string.

Subscribe to Our Newsletter

Sign up to receive updates/coupons/newsletters.

We don’t spam! Read our privacy policy for more info.

3 - Using ArduinoJSON assistant to generate code

I am not lying. The ArduinoJSON is really easy to use. They are not only providing detailed documentation but also even an ArduinoJSON assistant tool to generate code for you!

Visit https://arduinojson.org/v6/assistant/

ArduinoJSON Assistant Configuration
ArduinoJSON Assistant Configuration
Paste the JSON String from ip-api.com
Paste JSON string in ArduinoJSON Assistant
Paste JSON string in ArduinoJSON Assistant
We click the Next button until the final step
Get code from ArduinoJSON Assistant
Get code from ArduinoJSON Assistant

4 - Migrate the codes

Basically, the code from ArduinoJSON Assistant is pretty much ready to use.

The variable lat and lon are the data from the JSON string.

All we need to do is replace the input variable with the payload (we get from http get request)

And don’t forget to include the library.

#include <ArduinoJson.h>
				
					/**
   BasicHTTPClient.ino
    Created on: 24.05.2015
*/

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>

#include <WiFiClient.h>

#include <ArduinoJson.h>

ESP8266WiFiMulti WiFiMulti;

void setup() {

  Serial.begin(115200);
  // Serial.setDebugOutput(true);

  Serial.println();
  Serial.println();
  Serial.println();

  for (uint8_t t = 4; t > 0; t--) {
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("SSID", "PASSWORD");

}

void loop() {
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED)) {

    WiFiClient client;

    HTTPClient http;

    Serial.print("[HTTP] begin...\n");
    if (http.begin(client, "http://ip-api.com/json/?fields=lat,lon")) {  // HTTP


      Serial.print("[HTTP] GET...\n");
      // start connection and send HTTP header
      int httpCode = http.GET();

      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = http.getString();
          Serial.println(payload);

		// Stream& input;

		StaticJsonDocument<64> doc;

		DeserializationError error = deserializeJson(doc, payload);

		if (error) {
		  Serial.print(F("deserializeJson() failed: "));
		  Serial.println(error.f_str());
		  return;
		}

		float lat = doc["lat"]; // 22.2908
		float lon = doc["lon"]; // 114.1501

		Serial.println("Latitude: " + String(lat) + " | " + String(lon));

        }
      } else {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

      http.end();
    } else {
      Serial.printf("[HTTP} Unable to connect\n");
    }
  }

  delay(10000);
}
				
			

There you go. That’s all you need to parse JSON on Arduino/ESP8266/ESP32. Enjoy code.

Don’t forget to check our clarkwise touch screen.

close

Updates

Tips

Coupons

We don’t spam! Read our privacy policy for more info.

Leave a Reply