c++arduinoarduinojson

In ArduinoJson how can one check if an error occured when creating a JSON document?


In the ArduinoJson library, it is easy to create JSON entries as shown below.

StaticJsonDocument<512> json_doc;

String some_string = "Hello there!";
json_doc["some_string"] = some_string;

The question is what is the best way to check whether the entry was successfully created? This would allow error handling to be implemented and the error to be found quickly if the entries that are created change and grow over time.


Solution

  • Simply test to see whether the added node has a non-null value. If after you've tried to create a node, that node has a null value, the node was not created.

    Here's a simple Sketch to illustrate this test:

    #include <ArduinoJson.h>
    
    StaticJsonDocument<100> json_doc;
    int nodeNumber = 0;
    boolean ranOut = false;
    
    void setup() {
      Serial.begin(9600);
    }
    
    void loop() {
      if (ranOut) return;
    
      String nodeName(nodeNumber++);
      String nodeContent = nodeName + " thing";
      json_doc[nodeName] = nodeContent;
    
      if (!json_doc[nodeName]) {
        ranOut = true;
        Serial.print("Ran out at ");
        Serial.println(nodeNumber);
      }
    }
    

    When I ran this Sketch on my Arduino Uno, it produced:

    Ran out at 6
    

    That is, it created successfully created nodes json_doc["0"] through json_doc["5"] and ran out of space when it tried to create json_doc["6"].