Parsing JSON with ArduinoJson Library

Parsing JSON with ArduinoJson Library

JSON Example Data

  • Consider the following JSON data is being received by the Photon 2
{
  "place": {
    "city": "los angeles",
    "state": "california"
  },
  "temperature": [
    78,
    89,
    93,
    77
  ]
}

Parsing JSON with a Library: ArduinoJson

  • ArduinoJson is a popular library for parsing JSON code and can be installed from Workbench
  • Use the sample code below for your event handler
  • The first part allows for responses from the webhook that come in multiple parts (you don’t need to change this)
  • The second part is where you can adapt your own code

Configuration of ArduinoJson

  • Import library and set up Arduino compatibility
#define ARDUINOJSON_ENABLE_ARDUINO_STRING 1
#include <ArduinoJson.h> 

Publishing and Subscribing

void setup() {
  // Subscribe to the integration response event
  Particle.subscribe("hook-response/JSONWeatherStack", myHandler,
                     MY_DEVICES);
}

void loop() {
  // Get some data
  String data = "90089";
  // Trigger the integration
  Particle.publish("JSONWeatherStack", data, PRIVATE);
  // Wait 60 seconds
  delay(60000);
}

Parsing with ArduinoJson

Example: Consider the following JSON

{
  "place": {
    "city": "los angeles",
    "state": "california"
  },
  "temperature": [
    78,
    89,
    93,
    77
  ]
}

Configuration of ArduinoJson

  • Import library and set up Arduino compatibility
    #define ARDUINOJSON_ENABLE_ARDUINO_STRING 1
    #include <ArduinoJson.h> 
    

Configuration of Event Handler

  • The JSON will be passed to the data parameter of event handler
    void myHandler(const char *event, const char *data) {
    

Here is an example

void myHandler(const char *event, const char *data) {
//Part 1 allows for webhook responses to be delivered in multple "chunks"; you don't need to change this
    static String jsonBuffer; //store json response
    int responseIndex = 0;
    const char* slashOffset = strrchr(event, '/');
    if (slashOffset) responseIndex = atoi(slashOffset + 1);
    if (responseIndex == 0) jsonBuffer = "";
    jsonBuffer += data;

// Part 2 is where you can parse the actual data; you code goes in the IF
    DynamicJsonDocument doc(12288);
    DeserializationError error = deserializeJson(doc, jsonBuffer);

    if (!error) { // Test to see if was successful
        
    /* Here is where your parsing code goes */
    String city = doc["place"]["city"];  // "los angeles"
    int temp = doc["temperature"][1];  // 89
    Serial.println("The second temperature for " + city + " is " + String(temp));
    }

Credit

Updated: