Files
json/docs/mkdocs/docs/api/basic_json/index.md
T
satelliteprogrammer 40a62947d3 support JSON Merge Patch (RFC 7396) diff creation (#4965)
* support JSON Merge Patch (RFC 7396) diff creation

The JSON merge patch document format describes the set of modifications
to a resource's content, that more closely mimics the syntax of the
resource being modified.

However, and in contrast to JSON Patch (RFC 6902), a JSON Merge Patch
cannot express certain modifications, e.g., changing an array element
at a specific index, or setting a specific object value to null.
The null value in a JSON Merge Patch is used to remove the key from the
object.

The diff algorithm is not part of the RFC 7396, but it was tested
against all examples provided, plus additional cases on how null values
are handled.

Signed-off-by: Luís Murta <luis@murta.dev>

* improve algorithm efficiency

Signed-off-by: Luís Murta <luis@murta.dev>

* fix inconsistent nulls and empty arrays

Also add CHECKs for the patch, documentation and run `make amalgamate`.

Signed-off-by: Luís Murta <luis@murta.dev>

* documentation cleanups

Signed-off-by: Luís Murta <luis@murta.dev>

* add an iterative fallback to merge_diff

Bound the recursion depth like diff() and merge_patch(), and test values
nested past the bound.

Signed-off-by: Luís Murta <luis@murta.dev>

* address the remaining review comments

Signed-off-by: Luís Murta <luis@murta.dev>

* move multi-line raw strings out of CHECK macros

GCC 4.8/5, ICPC and NVHPC mis-tokenize multi-line raw string literals
inside macro arguments, breaking the build or the parsed JSON.

Signed-off-by: Luís Murta <luis@murta.dev>

---------

Signed-off-by: Luís Murta <luis@murta.dev>
2026-10-12 09:33:43 +02:00

19 KiB

nlohmann::basic_json

Defined in header <nlohmann/json.hpp>

template<
    template<typename U, typename V, typename... Args> class ObjectType = std::map,
    template<typename U, typename... Args> class ArrayType = std::vector,
    class StringType = std::string,
    class BooleanType = bool,
    class NumberIntegerType = std::int64_t,
    class NumberUnsignedType = std::uint64_t,
    class NumberFloatType = double,
    template<typename U> class AllocatorType = std::allocator,
    template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer,
    class BinaryType = std::vector<std::uint8_t>,
    class CustomBaseClass = void
>
class basic_json;

Template parameters

Template parameter Description Derived type
ObjectType type for JSON objects object_t
ArrayType type for JSON arrays array_t
StringType type for JSON strings and object keys string_t
BooleanType type for JSON booleans boolean_t
NumberIntegerType type for JSON integer numbers number_integer_t
NumberUnsignedType type for JSON unsigned integer numbers number_unsigned_t
NumberFloatType type for JSON floating-point numbers number_float_t
AllocatorType type of the allocator to use
JSONSerializer the serializer to resolve internal calls to to_json() and from_json() json_serializer
BinaryType type for binary arrays binary_t
CustomBaseClass extension point for user code json_base_class_t

The library imposes a number of requirements on these types that are not expressed as C++ concepts, such as the container operations object_t and array_t must provide, or the fact that StringType must be char-based. They are collected in Template Parameter Requirements.

Specializations

  • json - default specialization
  • ordered_json - a specialization that maintains the insertion order of object keys

Iterator invalidation

All operations that add values to an array (push_back , operator+=, emplace_back, insert, and operator[] for a non-existing index) can yield a reallocation, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.

For ordered_json, also all operations that add a value to an object (push_back, operator+=, emplace, insert, update, and operator[] for a non-existing key) can yield a reallocation, in which case all iterators (including the end() iterator) and all references to the elements are invalidated.

Requirements

The class satisfies the following concept requirements:

Basic

Layout

  • StandardLayoutType: JSON values have standard layout: All non-static data members are private and standard layout types, the class has no virtual functions or (virtual) base classes.

Library-wide

  • EqualityComparable: JSON values can be compared with ==, see operator==.
  • LessThanComparable: JSON values can be compared with <, see operator<.
  • Swappable: Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function swap.
  • NullablePointer: JSON values can be compared against std::nullptr_t objects which are used to model the null value.

Container

  • Container: JSON values can be used like STL containers and provide iterator access.
  • ReversibleContainer: JSON values can be used like STL containers and provide reverse iterator access.

Member types

Exceptions

  • exception - general exception of the basic_json class
    • parse_error - exception indicating a parse error
    • invalid_iterator - exception indicating errors with iterators
    • type_error - exception indicating executing a member function with a wrong type
    • out_of_range - exception indicating access out of the defined range
    • other_error - exception indicating other library errors

Container types

Type Definition
value_type #!cpp basic_json
reference #!cpp value_type&
const_reference #!cpp const value_type&
difference_type #!cpp std::ptrdiff_t
size_type #!cpp std::size_t
allocator_type #!cpp AllocatorType<basic_json>
pointer #!cpp std::allocator_traits<allocator_type>::pointer
const_pointer #!cpp std::allocator_traits<allocator_type>::const_pointer
iterator LegacyBidirectionalIterator
const_iterator constant LegacyBidirectionalIterator
reverse_iterator reverse iterator, derived from iterator
const_reverse_iterator reverse iterator, derived from const_iterator
iteration_proxy helper type for items function

JSON value data types

Parser callback

Member functions

Object inspection

Functions to inspect the type of a JSON value.

Optional functions to access the diagnostic positions.

  • start_pos - return the start position of the value
  • end_pos - return the one past the end position of the value

Value access

Direct access to the stored value of a JSON value.

Element access

Access to the JSON value

  • at - access specified element with bounds checking
  • operator[] - access specified element
  • value - access specified object element with default value
  • front - access the first element
  • back - access the last element

Lookup

  • find - find an element in a JSON object
  • count - returns the number of occurrences of a key in a JSON object
  • contains - check the existence of an element in a JSON object

Iterators

  • begin - returns an iterator to the first element
  • cbegin - returns a const iterator to the first element
  • end - returns an iterator to one past the last element
  • cend - returns a const iterator to one past the last element
  • rbegin - returns an iterator to the reverse-beginning
  • rend - returns an iterator to the reverse-end
  • crbegin - returns a const iterator to the reverse-beginning
  • crend - returns a const iterator to the reverse-end
  • items - wrapper to access iterator member functions in range-based for

Capacity

  • empty - checks whether the container is empty
  • size - returns the number of elements
  • max_size - returns the maximum possible number of elements

Modifiers

  • clear - clears the contents
  • push_back - add a value to an array/object
  • operator+= - add a value to an array/object
  • emplace_back - add a value to an array
  • emplace - add a value to an object if a key does not exist
  • erase - remove elements
  • insert - inserts elements
  • update - updates a JSON object from another object, overwriting existing keys
  • swap - exchanges the values

Lexicographical comparison operators

Serialization / Dumping

  • dump - serialization

Deserialization / Parsing

  • parse (static) - deserialize from a compatible input
  • accept (static) - check if the input is valid JSON
  • sax_parse (static) - generate SAX events

JSON Pointer functions

  • flatten - return flattened JSON value
  • unflatten - unflatten a previously flattened JSON value

JSON Patch functions

  • patch - applies a JSON patch
  • patch_inplace - applies a JSON patch in place
  • diff (static) - creates a diff as a JSON patch

JSON Merge Patch functions

Static functions

  • meta - returns version information on the library
  • get_allocator - returns the allocator associated with the container

Binary formats

  • from_bjdata (static) - create a JSON value from an input in BJData format
  • from_bon8 (static) - create a JSON value from an input in BON8 format
  • from_bson (static) - create a JSON value from an input in BSON format
  • from_cbor (static) - create a JSON value from an input in CBOR format
  • from_msgpack (static) - create a JSON value from an input in MessagePack format
  • from_ubjson (static) - create a JSON value from an input in UBJSON format
  • to_bjdata (static) - create a BJData serialization of a given JSON value
  • to_bon8 (static) - create a BON8 serialization of a given JSON value
  • to_bson (static) - create a BSON serialization of a given JSON value
  • to_cbor (static) - create a CBOR serialization of a given JSON value
  • to_msgpack (static) - create a MessagePack serialization of a given JSON value
  • to_ubjson (static) - create a UBJSON serialization of a given JSON value

Non-member functions

Literals

Helper classes

Examples

??? example

The example shows how the library is used.

```cpp
--8<-- "examples/README.cpp"
```

Output:

```json
--8<-- "examples/README.output"
```

See also

Version history

  • Added in version 1.0.0.