BasicJsonDocument<T> is the base class of DynamicJsonDocument. It’s a JsonDocument that allocates its memory pool using the allocator class T.

Use this class when you want to use a custom memory allocator; for example, when you want to use an external PSRAM found in many ESP32 boards. See examples below.

🆕 This class was added in ArduinoJson 6.10.0

The allocator class

The allocator class must implement two member functions:

struct Allocator {
  void* allocate(size_t);
  void deallocate(void*);
  void* reallocate(void*, size_t) ; // optional

allocate() is similar to malloc()

deallocate() is similar to free()

reallocate() is similar to realloc(). This member is optional and its only required if you call shrinkToFit().

Member functions

  • as<T>() casts the root to the specified type (e.g. JsonArray or JsonObject)
  • add() adds elements to the root array
  • capacity() returns the capacity of the memory pool
  • clear() empties the document and resets the memory pool
  • containsKey() tests if the root object contains the specified key
  • createNestedArray() creates a nested array attached to the root
  • createNestedObject() create a nested object attached to the root
  • getElement() is mostly for internal use 🤫
  • getMember() is mostly for internal use 🤫
  • getOrCreateMember() is mostly for internal use 🤫
  • operator[] gets or sets values in the document
  • is<T>() tests the type of the root
  • isNull() tells if the document is null or empty
  • memoryUsage() tells how many bytes are used in the memory pool
  • nesting() returns the number of nesting layers in the document
  • remove() removes an element (or member) at the specified index (or key)
  • set() is mostly for internal use 🤫
  • shrinkToFit() reduces the capacity of the memory pool to match the current usage
  • size() returns the number of elements (or members) that the root array (or object) contains
  • to<T>() clears the document and converts it to the specified type (e.g. JsonArray or JsonObject)



As as example here is how DynamicJsonDocument is defined:

struct DefaultAllocator {
  void* allocate(size_t size) {
    return malloc(size);

  void deallocate(void* ptr) {

  void* reallocate(void* ptr, size_t new_size) {
    return realloc(ptr, new_size);

typedef BasicJsonDocument<DefaultAllocator> DynamicJsonDocument;

External RAM on ESP32

To use the external SPI memory on an ESP32, you must call heap_caps_malloc(MALLOC_CAP_SPIRAM) instead of the usual malloc(). Such memory is available on the WROVER module.

The following SpiRamJsonDocument allocates its memory pool in the external RAM:

struct SpiRamAllocator {
  void* allocate(size_t size) {
    return heap_caps_malloc(size, MALLOC_CAP_SPIRAM);

  void deallocate(void* pointer) {

  void* reallocate(void* ptr, size_t new_size) {
    return heap_caps_realloc(ptr, new_size, MALLOC_CAP_SPIRAM);

typedef BasicJsonDocument<SpiRamAllocator> SpiRamJsonDocument;

See also