ArduinoJson
by Benoit Blanchon
ArduinoJson reads and writes JSON on small microcontrollers without the memory waste of a desktop JSON library. It is the standard way to build and parse the payloads used by REST APIs, MQTT messages and config files in ESP32 and ESP8266 projects. You put values into a JsonDocument with doc["key"] = value, turn it into text with serializeJson(), and read incoming JSON with deserializeJson().
The most common cause of errors is the version change from v6 to v7. In v6 you had to choose a size yourself with StaticJsonDocument<256> or DynamicJsonDocument(1024), and tools such as the ArduinoJson Assistant calculated it for you. In v7 there is a single JsonDocument that grows as needed, so those declarations are deprecated and capacity numbers from older tutorials no longer apply. Check which major version a tutorial was written for before copying its code. Other v7 changes to know: use doc["key"].is<int>() or doc["key"].isNull() instead of containsKey(), and use doc["list"].to<JsonArray>() to create arrays and objects.
Always check the result of deserializeJson(). It returns a DeserializationError that you can print with err.c_str(). InvalidInput means the text is not valid JSON (often a stray character, or an HTTP header that got mixed in). IncompleteInput means the data was cut off, usually because you read the response before all of it arrived or your buffer was too small. NoMemory means the device ran out of RAM, which on an Uno can happen even with modest documents.
Memory is the real constraint on small boards. On an ESP32 you can parse large responses comfortably, but on an Uno (2 KB of RAM) keep documents small and avoid copying strings. Two techniques help everywhere. The first is the default-value operator: doc["interval"] | 60 returns 60 when the key is missing, which avoids a whole class of bugs. The second is a filter, which lets you parse only the fields you need out of a large response such as a weather API, so the rest never uses memory.
When you fetch JSON over HTTP on an ESP32, call http.useHTTP10(true) and pass http.getStream() straight to deserializeJson(). This avoids chunked transfer encoding, which otherwise injects extra characters that cause InvalidInput errors, and it avoids holding the whole response as a String.
Setup
Installation
Arduino IDE — Library Manager
Sketch → Include Library → Manage Libraries → search ArduinoJson
PlatformIO
lib_deps = bblanchon/ArduinoJsonCompatibility
Supported boards
Code
Examples
Build and serialize a JSON payload (v7 API)
Create values, nested arrays and print compact or readable output. In v7 the document sizes itself.
#include <ArduinoJson.h>
void setup() {
Serial.begin(115200);
JsonDocument doc; // v7: grows automatically
doc["device"] = "esp32-01";
doc["temp"] = 24.5;
doc["online"] = true;
JsonArray readings = doc["readings"].to<JsonArray>();
readings.add(24.1);
readings.add(24.3);
readings.add(24.5);
serializeJson(doc, Serial); // compact, for sending
Serial.println();
serializeJsonPretty(doc, Serial); // readable, for debugging
}
void loop() {}Parse JSON with error checking and default values
Check the result of deserializeJson() every time, and use the | operator so a missing key gives a safe default instead of 0 or a crash.
const char* json = R"({"name":"sensor1","temp":21.7,"interval":30})";
JsonDocument doc;
DeserializationError err = deserializeJson(doc, json);
if (err) {
Serial.print(F("JSON error: "));
Serial.println(err.c_str()); // InvalidInput, IncompleteInput, NoMemory...
return;
}
const char* name = doc["name"] | "unknown"; // | gives a default if missing
float temp = doc["temp"] | 0.0;
int interval = doc["interval"] | 60;Keep only the fields you need with a filter
Parse a large API response while storing just a couple of values. The filter document lists the fields to keep, and everything else is discarded as it is read.
JsonDocument filter;
filter["main"]["temp"] = true;
filter["weather"][0]["description"] = true;
JsonDocument doc;
DeserializationError err = deserializeJson(
doc, payload, DeserializationOption::Filter(filter));
if (!err) {
float temp = doc["main"]["temp"];
const char* desc = doc["weather"][0]["description"];
}ESP32: parse a web API response straight from the stream
Using HTTP/1.0 avoids chunked encoding, so the stream contains only JSON and parses cleanly without storing the whole response in a String.
#include <HTTPClient.h>
#include <ArduinoJson.h>
HTTPClient http;
http.begin(url);
http.useHTTP10(true); // no chunked encoding
int code = http.GET();
if (code == 200) {
JsonDocument doc;
DeserializationError err = deserializeJson(doc, http.getStream());
if (!err) {
// use doc["..."] here
} else {
Serial.println(err.c_str());
}
}
http.end();Loop over an array of objects
The range-based for loop is the cleanest way to walk a list of items.
JsonDocument doc;
deserializeJson(doc, R"({"items":[{"id":1,"name":"LED"},{"id":2,"name":"Relay"}]})");
for (JsonObject item : doc["items"].as<JsonArray>()) {
int id = item["id"];
const char* name = item["name"];
Serial.print(id);
Serial.print(": ");
Serial.println(name);
}