ArduinoExplainerProgrammingTutorials/DIY

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:

  1. Open Arduino IDE.
  2. Go to Sketch > Include Library > Manage Libraries….
  3. Search for ArduinoJson.
  4. Click Install.

Parsing JSON Data in Arduino

To parse JSON data in Arduino, follow these steps:

  1. Create a JSON string.
  2. Use the ArduinoJson library to parse the JSON data.
  3. 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 and humidity 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

  1. Use StaticJsonDocument for small, fixed-size JSON objects: It reduces memory usage.
  2. Use DynamicJsonDocument for large or unpredictable JSON objects: It allocates memory dynamically.
  3. Check deserializeJson() for errors: Ensures reliable JSON parsing.
  4. Optimize memory usage: Keep JSON documents small when working with memory-constrained boards.
  5. 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

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *