This example shows how to generate a JSON document with ArduinoJson.

Source code

#include <ArduinoJson.h>

void setup() {
  // Initialize Serial port
  while (!Serial) continue;

  // Allocate the JSON document
  // Inside the brackets, 200 is the RAM allocated to this document.
  // Don't forget to change this value to match your requirement.
  // Use to compute the capacity.
  StaticJsonDocument<200> doc;

  // StaticJsonObject allocates memory on the stack, it can be
  // replaced by DynamicJsonDocument which allocates in the heap.
  // DynamicJsonDocument  doc(200);

  // Add values in the document
  doc["sensor"] = "gps";
  doc["time"] = 1351824120;

  // Add an array.
  JsonArray data = doc.createNestedArray("data");

  // Generate the minified JSON and send it to the Serial port.
  serializeJson(doc, Serial);
  // The above line prints:
  // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}

  // Start a new line

  // Generate the prettified JSON and send it to the Serial port.
  serializeJsonPretty(doc, Serial);
  // The above line prints:
  // {
  //   "sensor": "gps",
  //   "time": 1351824120,
  //   "data": [
  //     48.756080,
  //     2.302038
  //   ]
  // }

void loop() {
  // not used in this example

Classes used in this example

Functions used in this example

Keep learning

Mastering ArduinoJson

The chapter “Serialize with ArduinoJson” of Mastering ArduinoJson is a tutorial to learn how to generate JSON documents with the library. It begins with a simple example, like the one above, and then adds more features like serializing directly to a file or an HTTP request.

 X online