Files
json/docs/mkdocs/docs/home/architecture.md
T
Niels Lohmann 823eee3b59 Add editable json_documents: set, push_back, insert, and erase (#5630)
* Add editable json_documents: set, push_back, insert, and erase

basic_json_document gets a second template parameter, Editable
(false by default), plus the aliases json_editable_document,
json_editable_view, ordered_json_editable_document and
ordered_json_editable_view.

Editable documents can change values and structure without
rewriting the source text: set()/push_back() on values, keys,
array indices and JSON pointers; insert() before an array
element; erase() of an object key, array index or JSON pointer.

New values and element sequences go into edit storage that the
document owns and never moves, so views keep referring to their
value across edits and a parsed node never moves. Read-only
documents walk the plain node array and are unaffected.

Strings are checked for UTF-8 on entry, so dump() of an editable
document never throws type_error.316. Binary values cannot be
stored (type_error.319).

A seeded differential test applies random edits to an editable
document and to the equivalent ordered_json and compares both
after every step.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Fix old clang and MSVC C4127 in editable json documents

Value-initialize the const std::less in find_parent (clang 3.4/3.6 do not
implement DR 253), and test the Editable template argument through a
function to avoid MSVC C4127.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Copy nested values into a document without recursion

Counting and copying the nodes of a view or a basic_json value into an
editable document recursed once per nesting level, so that a deeply
nested value overflowed the stack. The four functions now walk the value
with an explicit stack, as materialize() does.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Do not leave a half-assigned container when set_moved() throws

assign() rewrote the kind, length and extent of a slot before set_moved()
registered its new element sequence. set_moved() can throw
(std::bad_alloc from reserving the bookkeeping vectors) for a slot that
is not moved yet, which left a container without the moved flag that
showed its old children. The bookkeeping is now reserved first
(reserve_moved()), so that nothing after the first write to the slot can
throw. block_of() reserves before it marks anything for the same reason.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Check strings copied from another document for valid UTF-8

An editable document only holds valid UTF-8, but copy_scalar() copied the
strings and keys of a view of another document unchecked. A document of
a weaker check (or a borrowed text that changed after parsing) could
therefore bring ill-formed UTF-8 into it. The copy is checked now, with
the error that dump() reports for the string; copies within the same
document stay unchecked.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Allow the edit arena to grow up to 4 GiB - 1 bytes

append_text() doubled the capacity of the arena and rejected the result
if it exceeded 4 GiB, so that an arena of more than 2 GiB could not grow
even though the 32-bit offsets of nodes address 4 GiB - 1 bytes. The
capacity is now clamped to that limit (text_capacity()), and an append
is rejected only if the bytes themselves do not fit.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Set a null value below a pointer as basic_json does

set(json_pointer, value) turned a null parent into an object for every
last reference token, so "/a/0" and "/a/-" below {"a":null} made
{"a":{"0":1}}, where basic_json's operator[](json_pointer) makes an
array. A null parent now becomes an array for "-" and for digit tokens
(filled with nulls up to the index) and an object otherwise. An invalid
index is reported before the parent changes.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Replace a container by a scalar in constant time once it is linked

Replacing an array or object that spans several nodes by a scalar looks
up its parent from the root (find_parent), which is linear in the size
of the document: setting every element of a 20,000 element array took
more than half a second. The parent only has to switch to links once;
afterward the extent of the replaced value no longer matters. Nodes that
an entry of a moved sequence links to are now marked (node_flags::linked),
and assign() skips the lookup for them.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Update the json_view banner and type_error.319 for editable documents

The banner still described a read-only view, and the documentation of
type_error.319 listed set and push_back only, although insert rejects
binary values as well.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Assign the member that lookups find when set() meets duplicate keys

An editable document reads the last member of a repeated key (as the
read-only document does), but set(object, key, value) assigned the first
one: a view taken from object[key] before the call did not show the new
value. It now assigns the last member's value, keeps the key at the
position of its first occurrence (where materialize() puts it), and drops
the other members.

The seeded differential test now also edits documents whose objects
repeat keys and compares every lookup (operator[], at, find, value,
contains, count, and JSON pointers) with the parsed basic_json value.
A targeted test covers duplicates before and after edits that move the
object, in large objects with an index, in moved arrays, and in values
copied from other documents.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Assign the first member when set() meets duplicate keys again

Lookups find the first member of a repeated key again, so set(object, key,
value) assigns that member (keeping the key where it is) and drops the
others, as documented before, and a view taken from object[key] shows the
new value. This undoes the code and documentation changes of 5cbb8e6d6.
Lookups in edited objects (navigation of editable documents) stop at the
first match, like those of parsed objects.

The tests that commit added expect the first member from lookups now. In the
seeded differential test, the documents with repeated keys repeat them after
the real members; the reference holds the first members, which the edits
address and the lookups are compared with, while materialize() is compared
with what parse() makes of the document's dump.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Fix MSVC C4127 in the lookups of editable json documents

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Fix clang-tidy 22 findings in the json_view headers

Silence bugprone-casting-through-void for the SSE loads (a reinterpret_cast
would trip -Wcast-align=strict), use auto for a cast initialiser, add
parentheses to a mixed expression, and name bugprone-std-namespace-modification
in the NOLINTs of the tuple_size/tuple_element specialisations.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
(cherry picked from commit 0effbaa7a2)

* Fix clang-tidy 22 findings in unit-json_view_edit.cpp and edit.hpp

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Keep a raw string with a backslash out of a CHECK (MSVC C2017)

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Make json_view.hpp pass include-what-you-use

ci_single_binaries runs IWYU with --error on every header. For json_view.hpp
it suggested adding <array> (std::array is used), and the headers that json.hpp
already provides (abi_config, abi_macros, input_adapters, json_pointer,
cpp_future, string_concat, value_t, json_fwd), plus <version> for
std::nullptr_t, and removing <cstddef> and edit_storage.hpp.

- include <array>
- keep <cstddef> (nullptr_t, size_t; IWYU attributes them to <version> and <cstring>)
- tell IWYU not to suggest the headers that json.hpp provides: the amalgamated
  json_view.hpp only includes json.hpp, so including them here would duplicate
  their definitions
- drop edit_storage.hpp, which edit.hpp includes

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Keep the view's edit headers clean for clang-tidy in C++17 mode

clang-tidy 22 checks the headers with -std=gnu++17 as well, where it asks
for a transparent comparator and std::make_unique. The regions map uses its
default comparator, and the allocation of the edit state keeps new (the
library is C++11) with a NOLINT.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Regenerate the amalgamated headers

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Follow the renames from the review of the view builder

The review of #5620 renamed document_data's tape/tape_size/tape_cap to
nodes/node_count/node_capacity and made the decode arena a
std::vector<char>; adapt the code of this change to it.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Expect count() to count every member in the edit tests

Since #5622, count() counts every member with the key, so documents
with duplicate keys no longer give 1.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Count matching keys as unsigned in the json_view edit tests

Like in the access test, adding the int result of the conditional to a
std::size_t fails -Werror=sign-conversion with GCC.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Address the review of erase() in editable json documents

From gregmarr's review of #5630:

- invalid_iterator.202 is thrown by overloads 1 and 2 only; the page said
  "every overload" and then excluded 3 in parentheses.
- The note on links says what moves (the links after the removed element,
  as insert() moves them the other way) and that every iterator over the
  container is invalidated, not only those after the removed element.
- edit.hpp compares keys with document_data::key_equals().

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Regenerate the amalgamated headers

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Address the review of editable json documents

From gregmarr's review of #5630:

- set() with a JSON pointer below a null value checks for "-" before
  scanning the token for digits.
- node_flags::storage is defined as escaped | edited, and the comment on
  document_data::base says that the fourth slot is unused.
- source_extent() names its root check.
- The integer-index overloads of set(), insert(), and erase() use a named
  trait instead of a negated condition, which astyle formats like the
  library's other enable_ifs.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Regenerate the amalgamated headers

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Address the rest of the review of editable json documents

From gregmarr's review of #5630:

- alloc_nodes() gives a request of half of the next chunk or more a chunk
  of its own, so that the rest of the current chunk stays available for
  smaller requests instead of being abandoned.
- The comments on edit_state, append_text(), and reserve_moved() say that
  views stay valid across every edit (not just the first), that n is 0 for
  empty strings, and why both capacities are checked.
- The architecture page names flag bits 3, 4, and 5 (linked) separately
  and says that a discarded view has no node; erase.md rewords overload 3
  and says why it never throws invalid_iterator.202.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Call alloc_nodes() before reading chunks.back() in the json_view chunk test

The operands of == are unsequenced, and MSVC evaluated
d->edits->chunks.back() before alloc_nodes() added the new chunk, so the
check compared the result with the previous chunk and failed on
msvc-arm64 (Debug and Release).

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

---------

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-21 10:21:29 +02:00

22 KiB

Architecture

This page gives a high-level overview of the library's architecture. It should help new contributors to get an idea of the used concepts and where to make changes.

Overview

The library is built around a single class template, nlohmann::basic_json. A basic_json value is a node in a tree of JSON values. All other components either create such a tree from an input (parsing), write a tree to an output (serialization), or give access to it (iterators, JSON Pointer, conversions).

flowchart LR
    input[/"input<br>(string, stream,<br>iterator range, file)"/]
    ia["input adapter"]
    lexer["lexer"]
    parser["parser"]
    breader["binary_reader"]
    sax["SAX interface"]
    value[("basic_json<br>value tree")]
    serializer["serializer"]
    bwriter["binary_writer"]
    oa["output adapter"]
    output[/"output<br>(string, stream,<br>vector)"/]

    input --> ia
    ia --> lexer --> parser --> sax
    ia --> breader --> sax
    sax --> value
    value --> serializer --> oa
    value --> bwriter --> oa
    oa --> output
  • JSON text is read by an input adapter, tokenized by the lexer, and turned into SAX events by the parser.
  • Binary formats (BJData, BON8, BSON, CBOR, MessagePack, UBJSON) are read by an input adapter and turned into the same SAX events by the binary_reader.
  • A SAX consumer receives the events. The one used by parse builds a basic_json value tree.
  • The serializer (JSON text) or the binary_writer (binary formats) writes a value tree to an output adapter.

Source layout

The public headers are in include/nlohmann:

Everything else lives in detail/ and namespace nlohmann::detail, which is not part of the public API. Paths below are relative to include/nlohmann.

Component Location
Value type enumeration detail/value_t.hpp
Input adapters detail/input/input_adapters.hpp
Lexer detail/input/lexer.hpp, detail/input/number_parse.hpp, detail/input/string_scan.hpp
Parser detail/input/parser.hpp
SAX interface and DOM builders detail/input/json_sax.hpp
Binary format readers detail/input/binary_reader.hpp
JSON serializer detail/output/serializer.hpp, detail/conversions/to_chars.hpp
Binary format writers detail/output/binary_writer.hpp
Output adapters detail/output/output_adapters.hpp
Iterators detail/iterators/
Conversions from/to arbitrary types detail/conversions/from_json.hpp, detail/conversions/to_json.hpp
JSON Pointer detail/json_pointer.hpp
Exceptions detail/exceptions.hpp
Type traits and C++ feature backports detail/meta/
Macros detail/macro_scope.hpp, detail/macro_unscope.hpp, detail/abi_macros.hpp

The single-header version single_include/nlohmann/json.hpp is generated from these files with make amalgamate and must not be edited by hand. The same command also generates single_include/nlohmann/json_view.hpp from json_view.hpp and detail/view/.

Template parameters

basic_json is parameterized by the types it uses to store values and to convert from and to other types:

Template parameter Default Used for
ObjectType std::map objects, see object_t
ArrayType std::vector arrays, see array_t
StringType std::string strings and object keys, see string_t
BooleanType bool Booleans, see boolean_t
NumberIntegerType std::int64_t signed integers, see number_integer_t
NumberUnsignedType std::uint64_t unsigned integers, see number_unsigned_t
NumberFloatType double floating-point numbers, see number_float_t
AllocatorType std::allocator allocating objects, arrays, strings, and binary values
JSONSerializer adl_serializer conversions from/to other types, see adl_serializer
BinaryType std::vector<std::uint8_t> binary values, see binary_t
CustomBaseClass void an optional base class, see json_base_class_t

The library provides two specializations:

The requirements on the template arguments are listed in Template Parameter Requirements.

Value storage

Each basic_json value stores its content as a tagged union: an enumeration value_t names the type of the value, and a union json_value holds the value itself. Both are members of the nested struct data, which is the only data member m_data of basic_json:

struct data
{
    /// the type of the current element
    value_t m_type = value_t::null;

    /// the value of the current element
    json_value m_value = {};
};

data m_data = {};

with

enum class value_t : std::uint8_t
{
    null,             ///< null value
    object,           ///< object (unordered set of name/value pairs)
    array,            ///< array (ordered collection of values)
    string,           ///< string value
    boolean,          ///< boolean value
    number_integer,   ///< number value (signed integer)
    number_unsigned,  ///< number value (unsigned integer)
    number_float,     ///< number value (floating-point)
    binary,           ///< binary array (ordered collection of bytes)
    discarded         ///< discarded by the parser callback function
};

union json_value {
  /// object (stored with pointer to save storage)
  object_t *object;
  /// array (stored with pointer to save storage)
  array_t *array;
  /// string (stored with pointer to save storage)
  string_t *string;
  /// binary (stored with pointer to save storage)
  binary_t *binary;
  /// boolean
  boolean_t boolean;
  /// number (integer)
  number_integer_t number_integer;
  /// number (unsigned integer)
  number_unsigned_t number_unsigned;
  /// number (floating-point)
  number_float_t number_float;
};

Objects, arrays, strings, and binary values are allocated on the heap with AllocatorType, and the union only stores a pointer to them. This keeps a basic_json value small: one pointer-sized union and one byte for the type. The class maintains the invariant that the pointer matching m_type is never null; assert_invariant() checks it with runtime assertions.

Node index of JSON views

A basic_json_document (see Zero-copy JSON views) does not build a tree of values. Its parser (detail/view/builder.hpp) writes a flat array of 16-byte nodes, one per value and one per object key, in document order. A basic_json_view is a pointer to the document and a pointer to one node. The layout is struct node in detail/view/node.hpp (the numbers are bit offsets, 32 bits per row):

packet-beta
  0-7: "kind"
  8-15: "flags"
  16-31: "extra"
  32-63: "off"
  64-95: "len"
  96-127: "next"
Bytes Field Type Contents
0 kind uint8_t the type, numbered as value_t: 0 null, 1 object, 2 array, 3 string, 4 boolean, 5 signed integer, 6 unsigned integer, 7 float; 10 for a link (see below). There is no node for a discarded value: a discarded view has none
1 flags uint8_t bits 0-1: where a string's bytes (or a number's token) are (0: the source text, 1: the buffer of decoded strings, for strings with escapes, 2: the edit buffer); bit 2: the value of a boolean; bit 3: moved, bit 4: new, bit 5: linked (see below)
2-3 extra uint16_t numbers: the number of integer digits (low byte) and fraction digits (high byte), 255 for more; objects: the number of their key hash index (1-based), or 0; otherwise 0
4-7 off uint32_t where the value starts: the first byte after a string's opening quote (or its position in the buffer of decoded strings), the first byte of a number or literal, the bracket of an array or object
8-11 len uint32_t strings: the length after decoding; floats and literals: the length of the token; arrays and objects: the number of elements
12-15 next uint32_t arrays and objects: the number of nodes of the subtree, including the node itself
  • Integers keep their converted value in bytes 8-15 instead of len and next; the length of their token follows from the number of digits in extra (and the sign). Non-negative integers are unsigned integers, as with parse.
  • Floats keep only their token. The digit layout in extra lets the conversion read the digits without scanning the token again, and only when the value is read.
  • Object members are the node of the key (a string) followed by the nodes of the value.
  • Navigation needs no pointers: the elements of an array or object follow its node, and the node after a value's subtree is next nodes further for an array or object, and the next node otherwise (document_data::after). Views step from element to element this way and skip whole subtrees in constant time.
  • Offsets are 32 bits wide, so a document is limited to 4294967279 bytes, 4 GiB minus 16 bytes (a margin below 2^32 for positions one scanner step past the end of the text; out_of_range.416).
  • Large objects (128 members or more) get a hash index for their keys after parsing (detail/view/object_index.hpp): an open-addressing table whose slots hold the distance from the object's node to a key's node, so that a lookup does not compare every key. Of duplicate keys the table leads to the first, as a linear search does. The object's extra holds the number of its table. Only 65,535 tables fit into extra; objects beyond them are searched linearly.

For example, #!json {"a": [1, 2.5]} becomes five nodes. Each node's elements follow it, and next leads from an array or object past its subtree:

flowchart LR
    n0["0: object<br>len 1, next 5"]
    n1["1: key a"]
    n2["2: array<br>len 2, next 3"]
    n3["3: unsigned integer 1"]
    n4["4: float 2.5"]
    e(["end"])
    n0 --> n1 --> n2 --> n3 --> n4 --> e
    n0 -. next .-> e
    n2 -. next .-> e
Node kind extra off len next
0 1 (object) 0 0 1 5
1 3 (string) 0 2 1 0
2 2 (array) 0 6 2 3
3 6 (unsigned integer) 0x0001 7 - -
4 7 (float) 0x0101 10 3 0

All flags are 0. The integer's bytes 8-15 hold its value, 1; its extra says it has one digit. The float's extra says it has one integer and one fraction digit, and its len is that of the token 2.5.

Editable documents (json_editable_document, detail/view/edit.hpp and detail/view/edit_storage.hpp) never write the source text and never move or resize the parsed index, so views stay valid while the document is edited:

  • A new scalar is written over its node. Its text (a string, or the token of a number as dump() writes it) goes to the edit buffer, which flags bits 0-1 then name.
  • An array or object whose elements change gets the flag moved (bit 3): its elements then live in a separate sequence (a header node, then the entries), whose number is in off. The entries are links (kind 10), whose bytes 8-15 hold the address of the value's node, so values never move.
  • A node written by an edit gets the flag new (bit 4): it has no position in the source text.
  • A value that an entry of such a sequence links to gets the flag linked (bit 5): its extent in the parsed layout (next) no longer matters, so a scalar can replace an array or object there in place.
  • Views of read-only documents compile without any of this: how views walk the index is a template parameter (navigation<Editable>).

Input adapters

Input is read via input adapters that abstract a source. Every input adapter provides this interface:

/// the type of the characters in the input
using char_type = ...;

/// read a single character; returns std::char_traits<char_type>::eof() at the end of the input
typename std::char_traits<char_type>::int_type get_character();

/// read up to count * sizeof(T) bytes into dest and return the number of bytes read
/// (used by the binary readers)
template<class T>
std::size_t get_elements(T* dest, std::size_t count = 1);

The lexer detects two optional extensions at compile time. Only iterator_input_adapter provides them, and only for random-access input of single-byte characters:

  • supports_seek, get_consumed_count(), and copy_consumed_range() let the lexer reconstruct already consumed input for error messages instead of copying every character it reads. With get_read_count() and count_consumed_lines(), the lexer also derives the read position from the adapter and counts lines only when an error needs them, instead of counting characters and lines on every read.
  • supports_bulk_scan, bulk_data(), bulk_remaining(), and bulk_skip() let the lexer scan strings directly in contiguous memory, several bytes at a time, and skip the spaces that indent a line in 8-byte steps.

The function input_adapter picks the right adapter for the argument passed to parse, accept, sax_parse, or the from_* functions:

  • iterator_input_adapter reads from an iterator range, which also covers strings, containers, and pointers.
  • wide_string_input_adapter reads from ranges of wchar_t, char16_t, or char32_t and converts them to UTF-8. It cannot be used for binary formats; its get_elements() throws.
  • input_stream_adapter reads from a std::istream.
  • file_input_adapter reads from a std::FILE*.

SAX interface

The parser does not build values itself. It reports what it reads as events to a SAX consumer, which implements the interface json_sax: null, boolean, number_integer, number_unsigned, number_float, string, binary, start_object, key, end_object, start_array, end_array, and parse_error.

The library comes with two consumers in detail/input/json_sax.hpp:

  • json_sax_dom_parser builds a basic_json value tree. parse uses it.
  • json_sax_dom_callback_parser does the same, but calls a parser callback for each event, which can skip values. parse uses it when a callback is given.

The binary_reader emits the same events for binary formats, so sax_parse works with a user-defined consumer for JSON and for all binary formats alike.

Output adapters

Output is written via output adapters:

void write_character(CharType c);

void write_characters(const CharType* s, std::size_t length);

The serializer (used by dump and operator<<) and the binary_writer (used by the to_* functions) write to one of these adapters:

  • output_vector_adapter appends to a std::vector.
  • output_stream_adapter writes to a std::ostream.
  • output_string_adapter appends to a string.

Value conversion

Values are converted from and to other types with the JSONSerializer template parameter. The default, adl_serializer, calls the free functions

template<class T>
void to_json(basic_json& j, const T& t);

template<class T>
void from_json(const basic_json& j, T& t);

found by argument-dependent lookup. The library defines them for standard types in detail/conversions; users add them for their own types, see Arbitrary Type Conversions. The serialization macros generate these functions.

Additional features

Details namespace

Namespace nlohmann::detail contains all implementation details. It is not part of the public API and may change in any release. Besides the components above, it contains:

  • type traits to detect the capabilities of user-defined types (detail/meta/type_traits.hpp),
  • backports of C++14/17 features to C++11 (detail/meta/cpp_future.hpp), and
  • helpers such as string_concat and string_escape.