- bblanchon/ArduinoJson
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Decoding and Encoding JSON with Arduino or ESP8266
- What is JSON?
- JSON syntax basics
- JSON examples
- Arduino with Ethernet shield
- Preparing the Arduino IDE
- Features
- Compatible with
- Installing the ArduinoJson library
- Decoding JSON – Parse JSON string
- OpenWeatherMap API
- Making an API Request with Arduino
- Modifying the code for your project
- STEP #1 – struct
- STEP #2 – JsonBuffer size
- STEP #3 – accessing the decoded data
- Demonstration
- Encoding JSON – Generate JSON string
- Encoding example with Arduino and Node-RED
- Creating the flow
- Send JSON data with Arduino
- Modifying the code for your project
- sendRequest() function
- Demonstration
- Wrapping up
bblanchon/ArduinoJson
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
ArduinoJson is a C++ JSON library for Arduino and IoT (Internet Of Things).
- JSON deserialization
- Optionally decodes UTF-16 escape sequences to UTF-8
- Optionally stores links to the input buffer (zero-copy)
- Optionally supports comments in the input
- Optionally filters the input to keep only desired values
- Supports single quotes as a string delimiter
- Compatible with NDJSON and JSON Lines
- JSON serialization
- Can write to a buffer or a stream
- Optionally indents the document (prettified JSON)
- MessagePack serialization
- MessagePack deserialization
- Efficient
- Twice smaller than the «official» Arduino_JSON library
- Almost 10% faster than the «official» Arduino_JSON library
- Consumes roughly 10% less RAM than the «official» Arduino_JSON library
- Fixed memory allocation, no heap fragmentation
- Optionally works without heap memory (zero malloc)
- Deduplicates strings
- Versatile
- Supports custom allocators (to use external RAM chip, for example)
- Supports String , std::string , and std::string_view
- Supports Stream and std::istream / std::ostream
- Supports Flash strings
- Supports custom readers and custom writers
- Supports custom converters
- Portable
- Usable on any C++ project (not limited to Arduino)
- Compatible with C++98, C++11, C++14 and C++17
- Zero warnings with -Wall -Wextra -pedantic and /W4
- Header-only library
- Works with virtually any board
- Arduino boards: Uno, Due, Micro, Nano, Mega, Yun, Leonardo.
- Espressif chips: ESP8266, ESP32
- Lolin (WeMos) boards: D1 mini, D1 Mini Pro.
- Teensy boards: 4.0, 3.2, 2.0
- Particle boards: Argon, Boron, Electron, Photon.
- Texas Instruments boards: MSP430.
- Soft cores: Nios II.
- Tested on all major development environments
- Arduino IDE
- Atmel Studio
- Atollic TrueSTUDIO
- Energia
- IAR Embedded Workbench
- Keil uVision
- MPLAB X IDE
- Particle
- PlatformIO
- Sloeber plugin for Eclipse
- Visual Micro
- Visual Studio
- Even works with online compilers like wandbox.org
- CMake friendly
- Well designed
- Elegant API
- Thread-safe
- Self-contained (no external dependency)
- const friendly
- for friendly
- TMP friendly
- Handles integer overflows
- Well tested
- Unit test coverage close to 100%
- Continuously tested on
- Visual Studio 2010, 2012, 2013, 2015, 2017, 2019, 2022
- GCC 4.4, 4.6, 4.7, 4.8, 4.9, 5, 6, 7, 8, 9, 10, 11
- Clang 3.5, 3.6, 3.7, 3.8, 3.9, 4.0, 5.0, 6.0, 7, 8, 9, 10
- Continuously fuzzed with Google OSS Fuzz
- Passes all default checks of clang-tidy
- Well documented
- Tutorials
- Examples
- How-tos
- FAQ
- Troubleshooter
- Book
- Changelog
- Vibrant user community
- Most popular of all Arduino libraries on GitHub
- Used in hundreds of projects
- Responsive support
- Discord server
Here is a program that parses a JSON document with ArduinoJson.
Here is a program that generates a JSON document with ArduinoJson:
ArduinoJson is thankful to its sponsors. Please give them a visit; they deserve it!
If you run a commercial project that embeds ArduinoJson, think about sponsoring the library’s development: it ensures the code that your products rely on stays actively maintained. It can also give your project some exposure to the makers’ community.
If you are an individual user and want to support the development (or give a sign of appreciation), consider purchasing the book Mastering ArduinoJson ❤ , or simply cast a star ⭐ .
About
? JSON library for Arduino and embedded C++. Simple and efficient.
Decoding and Encoding JSON with Arduino or ESP8266
In this blog post you’re going to learn how to decode (parse a JSON string) and encode (generate a JSON string) with the ArduinoJson library using the Arduino with the Ethernet shield. This guide also works with the ESP8266 and ESP32 Wi-Fi modules with small changes.
Important: this tutorial is only compatible with the ArduinoJSON library 5.13.5.
What is JSON?
JSON stands for JavaScript Object Notation. JSON is a lightweight text-based open standard design for exchanging data.
JSON is primarily used for serializing and transmitting structured data over network connection – transmit data between a server and a client. It is often used in services like APIs (Application Programming Interfaces) and web services that provide public data.
JSON syntax basics
In JSON, data is structured in a specific way. JSON uses symbols like < >, : ” ” [ ] and it has the following syntax:
- Data is represented in key/value pairs
- The colon (:) assigns a value to key
- key/value pairs are separated with commas (,)
- Curly brackets hold objects (< >)
- Square brackets hold arrays ([ ])
For example, to represent data in JSON, the key/value pairs come as follows:
JSON examples
In a real world example, you may want structure data about a user:
Or in a IoT project, you may want to structure data from your sensors:
In JSON, the values can be another JSON object (sports) or an array (pets) . For example:
Here we are structuring data about a user and we have several keys: “name”, “sports” and “pets”.
The name has the value Rui assigned. Rui may practice different sports relating to where they are practiced. So, we create another JSON object to save Rui’s favorite sports. This JSON object is the value of the “sports” key.
The “pets” key has an array that contains Rui’s pets’ names and it has the values “Max” and “Dique” inside.
Most APIs return data in JSON and most values are JSON objects themselves. The following example shows the data provided by a weather API.
This API provides a lot of information. For example, the first lines store the coordinates with the longitude and latitude.
Arduino with Ethernet shield
The examples in this post use an Arduino with an Ethernet shield. Just mount the shield onto your Arduino board and connect it to your network with an RJ45 cable to establish an Internet connection (as shown in the figure below).
Note: the examples provided in this tutorial also work with the ESP8266 and ESP32 with small changes.
Preparing the Arduino IDE
The easiest way to decode and encode JSON strings with the Arduino IDE is using the ArduinoJson library 5.13.5 which was designed to be the most intuitive JSON library, with the smallest footprint and most efficiently memory management for Arduino.
It has been written with Arduino in mind, but it isn’t linked to Arduino libraries so you can use this library in any other C++ project. There’s also a documentation website for the library with examples and with the API reference.
Features
- JSON decoding (comments are supported)
- JSON encoding (with optional indentation)
- Elegant API, very easy to use
- Fixed memory allocation (zero malloc)
- No data duplication (zero copy)
- Portable (written in C++98)
- Self-contained (no external dependency)
- Small footprint
- Header-only library
- MIT License
Compatible with
- Arduino boards: Uno, Due, Mini, Micro, Yun…
- ESP8266, ESP32 and WeMos boards
- Teensy, RedBearLab boards, Intel Edison and Galileo
- PlatformIO, Particle and Energia
Installing the ArduinoJson library
For this project you need to install the ArduinoJson library in your Arduino IDE:
- Click here to download the ArduinoJson version 5.13.5. You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get ArduinoJson-master folder
- Rename your folder from ArduinoJson-master to ArduinoJson
- Move the ArduinoJson folder to your Arduino IDE installation libraries folder
- Finally, re-open your Arduino IDE
Decoding JSON – Parse JSON string
Let’s start by decoding/parsing the next JSON string:
Import the ArduinoJson library:
Arduino JSON uses a preallocated memory pool to store the JsonObject tree, this is done by the StaticJsonBuffer. You can use ArduinoJson Assistant to compute the exact buffer size, but for this example 200 is enough.
Create a char array called json[] to store a sample JSON string:
Use the function parseObject() to decode/parse the JSON string to a JsonObject called root.
To check if the decoding/parsing was successful, you can call root.success():
The result can be false for three reasons:
- the JSON string has invalid syntax;
- the JSON string doesn’t represent an object;
- the StaticJsonBuffer is too small – use ArduinoJson Assistant to compute the buffer size.
Now that the object or array is in memory, you can extract the data easily. The simplest way is to use the JsonObject root:
You can use the decoded variables sensor, time, latitude or longitude in your code logic.
OpenWeatherMap API
For a real example using an Arduino with an Ethernet shield, we’re going to use a free API from OpenWeatherMap to request the day’s weather forecast for your chosen location.
Learning to use APIs is a great skill because it allows you access to a wide variety of constantly-changing information, such as the current stock price, the currency exchange rate, the latest news, traffic updates, and much more.
Using the API
OpenWeatherMap’s free plan provides everything you need for thins example. To use the API you need an API key, known as the APIID. To get an APIID:
- Open a browser and go to OpenWeatherMap
- Press the Sign up button and create a free account
- Once your account is created, you’ll be presented with a dashboard that contains several tabs (see figure below)
- Select the API Keys tab and copy your unique Key
This is a unique key you need to pull information from the site. Copy and paste this key somewhere, you’ll need it in a moment.
To pull information on weather in your chosen location, enter the following URL with the sections in curly brackets replaced with your chosen location information and your unique API key:
Replace with the city you want data for, with the country code for that city, and with your unique API key we found previously. For example, our API URL for the town of Porto in Portugal, after replacing with the details, would be:
Note: more information on using the API to get weather information is available here.
Copy your URL into your browser and it should give you a bunch of information that corresponds to your local weather information.
In our case, it returns the weather in Porto, Portugal on the day of writing:
Making an API Request with Arduino
Now that you have a URL that returns your local weather data. You can automate this task and access that data in your Arduino or ESP8266 projects. Here’s the full script that you need to upload to your Arduino with Ethernet shield to return the temperature in Kelvin and humidity:
Note: make sure your replace the resource variable with your unique OpenWeatherMap URL resource:
Modifying the code for your project
In this example, the Arduino performs an HTTP GET request to a desired service (in this case the OpenWeatherMap API), but you could change it to request any other web service. We won’t explain the Arduino code line by line.
For this project it’s important that you understand what you need to change in the Arduino code to decode/parse any JSON response. Follow these next three steps.
STEP #1 – struct
Create a data structure that can store the information that you’ll want to extract from the API. In this case, we want to store the temperature and humidity in char arrays:
STEP #2 – JsonBuffer size
Go to the ArduinoJson Assistant and copy the full OpenWeatherMap API response to the Input field.
Copy the Expression generated (see the preceding figure), in my case:
You’ll need to edit the readReponseContent() function with your the generated JsonBuffer size from ArduinoJson Assistant to allocate the appropriate memory for decoding the JSON response from an API:
Still inside the readReponseContent() function you need to copy the variables that you need for your project to your struct data:
STEP #3 – accessing the decoded data
Then, you can easily access the decoded JSON data in your Arduino code and do something with it. In this example we’re simply printing the temperature in Kelvin and humidity in the Arduino IDE serial monitor:
Demonstration
Open the Arduino IDE serial monitor at a baud rate of 9600 and you’ll see the temperature in Kelvin and the humidity in percentage being printed in the Serial monitor every 60 seconds.
You can access the rest of the information in the OpenWeatherMap API response, but for demonstration purposes we only decoded the temperature and humidity.
Encoding JSON – Generate JSON string
Let’s learn how to encode/generate the next JSON string:
You can read the docs about enconding here.
Import the ArduinoJson library:
Arduino JSON uses a preallocated memory pool to store the object tree, this is done by the StaticJsonBuffer. You can use ArduinoJson Assistant to compute the exact buffer size, but for this example 200 is enough.
Create a JsonObject called root that will hold your data. Then, assign the values gps and 1351824120 to the sensor and time keys, respectively:
Then, to hold an array inside a data key, you do the following:
It is very likely that you’ll need to print the generated JSON in your Serial monitor for debugging purposes, to do that:
After having your information encoded in a JSON string you could post it to another device or web service as shown in the next example.
Encoding example with Arduino and Node-RED
For this example you need to Node-RED or a similar software that can receive HTTP POST requests. You can install Node-RED on your computer, but I recommend running Node-RED on a Raspberry Pi.
Creating the flow
In this flow, you’re going to receive an HTTP POST request and print the receive data in the Debug window. Follow these next 6 steps to create your flow:
1) Open the Node-RED software in your browser
2) Drag an HTTP input node and a debug node
3) Edit the HTTP input by adding the POST method and the /json-post-example URL
4) You can leave the default settings for the debug node
5) Connect your nodes
6) To save your application, you need to click the deploy button on the top right corner
Your application is saved and ready.
Send JSON data with Arduino
After having Node-RED prepared to receive POST requests at the /json-post-example URL, you can use the next code example on an Arduino with an Ethernet shield to send data to it.
Note: make sure your replace the server variable with your Raspberry Pi IP address:
Modifying the code for your project
In this example, the Arduino performs an HTTP POST request to Node-RED, but you could change it to make request another web service or server. We won’t explain the Arduino code line by line. For this project it’s important that you understand what you need to change in the Arduino code to encode/generate a JSON request.
sendRequest() function
For this project you can modify the sendRequest() function with your own JSON data structure:
Start by reserving memory space for your JSON data. You can use ArduinoJson Assistant to compute the exact buffer size, but for this example 200 is enough.
Create a JsonObject called root that will hold your data and assign the values to your keys (in this example we have the sensor key):
To hold data inside an array, you do the following:
Print the generated JSON string in the Arduino IDE serial monitor for debugging purposes:
The rest of the sendRequest() function is the POST request.
Note that you can use the root.measureLength() to determine the length of your generated JSON. The root.printTo(client) send the JSON data to the Ethernet client.
Demonstration
Open the Arduino IDE serial monitor at a baud rate of 9600 and you’ll see the JSON object printed in the serial monitor every 60 seconds.
In the Node-RED debug tab you’ll see the same JSON object being receive every 60 seconds:
Finally, you create functions in Node-RED that do something useful with the received data, but for demonstration purposes we’re just printing the sample data.
Wrapping up
In this tutorial we’ve shown you several examples on how to decode and encode JSON data. You can follow these basic steps to build more advanced projects that require exchanging data between devices.
We hope you’ve found this tutorial useful.
If you liked this project and Home Automation make sure you check our course: Build a Home Automation System for $100.