JSON Parsing in Arduino IDE
JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used for transmitting data between a server and a client. Arduino projects often require parsing JSON data when dealing with APIs, IoT applications, and sensor data processing. In this article, we will explore JSON parsing in the Arduino IDE using the ArduinoJson library.
Why Use JSON in Arduino?
JSON is preferred in Arduino projects because:
- It is lightweight and easy to read.
- It provides a structured format for sending and receiving data.
- It is widely supported in web-based APIs, making it ideal for IoT applications.
Installing the ArduinoJson Library
To work with JSON in Arduino, we use the ArduinoJson library. Follow these steps to install it:
- Open Arduino IDE.
- Go to Sketch > Include Library > Manage Libraries….
- Search for ArduinoJson.
- Click Install.
Parsing JSON Data in Arduino
To parse JSON data in Arduino, follow these steps:
- Create a JSON string.
- Use the
ArduinoJson
library to parse the JSON data. - Extract values from the JSON object.
Example: Parsing a Simple JSON String
#include <ArduinoJson.h>
void setup() {
Serial.begin(9600);
// Sample JSON string
const char* json = "{\"temperature\": 25, \"humidity\": 60}";
// Create a JSON document
StaticJsonDocument<200> doc;
// Deserialize (parse) the JSON string
DeserializationError error = deserializeJson(doc, json);
if (error) {
Serial.print("JSON Parsing failed: ");
Serial.println(error.c_str());
return;
}
// Extract values
int temperature = doc["temperature"];
int humidity = doc["humidity"];
// Print extracted values
Serial.print("Temperature: ");
Serial.println(temperature);
Serial.print("Humidity: ");
Serial.println(humidity);
}
void loop() {
// Nothing here
}
Explanation:
- We define a JSON string containing
temperature
andhumidity
values. - We create a
StaticJsonDocument
object to hold the parsed data. - We use
deserializeJson()
to parse the JSON string. - We extract and print the values.
Parsing JSON Data from Serial Input
Sometimes, JSON data is received from a serial device or API response. Here’s how to handle it:
#include <ArduinoJson.h>
void setup() {
Serial.begin(9600);
Serial.println("Send JSON data:");
}
void loop() {
if (Serial.available() > 0) {
String json = Serial.readString(); // Read input from serial
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, json);
if (error) {
Serial.print("JSON Parsing failed: ");
Serial.println(error.c_str());
return;
}
int value = doc["sensor_value"];
Serial.print("Sensor Value: ");
Serial.println(value);
}
}
Explanation:
- The Arduino waits for JSON input via the Serial Monitor.
- It reads the input string and parses it.
- It extracts the
sensor_value
from the JSON data.
Generating JSON Data in Arduino
Arduino can also generate JSON data to send to a server or another device.
Example: Creating JSON Data
#include <ArduinoJson.h>
void setup() {
Serial.begin(9600);
StaticJsonDocument<200> doc;
// Add data to JSON object
doc["device"] = "Arduino";
doc["status"] = "active";
doc["battery"] = 85;
// Convert JSON object to string
String jsonString;
serializeJson(doc, jsonString);
// Print JSON string
Serial.println(jsonString);
}
void loop() {
// Nothing here
}
Explanation:
- We create a JSON document.
- We add key-value pairs (
device
,status
,battery
). - We use
serializeJson()
to convert it into a JSON string. - The JSON string is printed to the Serial Monitor.
Best Practices for JSON Parsing in Arduino
- Use
StaticJsonDocument
for small, fixed-size JSON objects: It reduces memory usage. - Use
DynamicJsonDocument
for large or unpredictable JSON objects: It allocates memory dynamically. - Check
deserializeJson()
for errors: Ensures reliable JSON parsing. - Optimize memory usage: Keep JSON documents small when working with memory-constrained boards.
- Use Serial Monitor for debugging: Helps visualize the JSON data being parsed.
Conclusion
JSON parsing in Arduino is essential for working with APIs, IoT applications, and sensor data. The ArduinoJson
library simplifies the process, allowing easy data extraction and manipulation. By following these techniques, you can efficiently send and receive structured JSON data in your Arduino projects.
Read This: Understanding Basic Functions in Arduino IDE