* docs: new design for the documentation site Apply the brand to the Material for MkDocs site: Inter and JetBrains Mono served by the site (upright and real italic), brand colours, blue header band with the syntax pattern, wordmark in the header, new home page (hero, cards, animated feature tour), 404 page, polish for tabs, search, footer, focus rings, tables and code blocks, and theme features (code copy, previous/next footer, TOC follow, search suggestions). Draw the number railroad diagram, the parser callback events and the iterator illustrations as inline SVGs that follow the light and dark scheme. The generator scripts are in docs/mkdocs/scripts/figures; the feature slideshow (json-light.svg, json-dark.svg, replacing json.gif on the home page) is built by docs/mkdocs/scripts/slideshow. Decision nodes in five flowcharts become hexagons, which need far less room. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: add figures, table captions and a macro chooser - Figures with numbered captions: SAX stepper, json_view layout and edit stepper, exception map, JSON pointer and patch walkers, QA pipeline, scaling and binary size charts, roadmap lanes, release timeline, integration decision tree and namespace builder - Table captions (nj-table-caption) on 9 pages - Compile times: modules and PCH charts, filesystem section, re-measured Figure 1, links between features/modules.md and compile_times.md - Interactive macro chooser for features/arbitrary_types.md - Link check: exclude URLs that answer the plugin with 400/401/419 or are dead (customers.md) Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: macro chooser generates adl_serializer for non-default-constructible types Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: cross-link concept pages and API pages in See also sections Add See also links in both directions between the concept pages (features, home, integration) and the API pages, write API links in code font, give every entry a comment after a dash, and show the callback event figure on the parser callbacks page. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: address review comments on the new design - Home: add a "Latest release" button - Sponsors: update the list and group it by tier - Features: list all feature pages on the index page - Releases: add highlights per release, link the 4.0 roadmap, add the first commit to the timeline - Exceptions: prefix all example messages with the exception name - API: no code font for format names in the See also links of the to_/from_ pages - Merge Patch: show the document before, the patch, and the result - Replace "--" with typographic dashes, mark external links with an icon, center Mermaid diagrams Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
21 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
Documents and views
Besides basic_json, the library offers a second way to hold a parsed JSON text: a
basic_json_document, which owns or borrows the text and holds a flat index of the
values in it, and a basic_json_view, a read-only handle to one value of such a document.
Both are defined in the header <nlohmann/json_view.hpp>; see
Zero-copy JSON views for the concept and the trade-offs.
- json_document / ordered_json_document - read-only
documents of the
basic_jsonspecialization they belong to - json_editable_document / ordered_json_editable_document - documents that can be modified in place
- json_view / ordered_json_view - views of a document
- json_editable_view / ordered_json_editable_view - views of an editable document
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
- DefaultConstructible: JSON values can be default-constructed. The result will be a JSON null value.
- MoveConstructible: A JSON value can be constructed from an rvalue argument.
- CopyConstructible: A JSON value can be copy-constructed from an lvalue expression.
- MoveAssignable: A JSON value can be assigned from an rvalue argument.
- CopyAssignable: A JSON value can be copy-assigned from an lvalue expression.
- Destructible: JSON values can be destructed.
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
==, seeoperator==. - LessThanComparable: JSON values can be compared with
<, seeoperator<. - 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_tobjects which are used to model thenullvalue.
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
- adl_serializer - the default serializer
- value_t - the JSON type enumeration
- json_pointer - JSON Pointer implementation
- json_serializer - type of the serializer to for conversions from/to JSON
- error_handler_t - type to choose behavior on decoding errors
- bjdata_version_t - type to choose the BJData version to write
- cbor_tag_handler_t - type to choose how to handle CBOR tags
- initializer_list_t - type for initializer lists of
basic_jsonvalues - input_format_t - type to choose the format to parse
- json_sax_t - type for SAX events
- with_object_t, with_array_t, with_string_t, with_boolean_t, with_integers_t, with_float_t, with_allocator_t,
with_json_serializer_t, with_binary_t, with_base_class_t - types to create a
basic_jsontype with one (or two) replaced template parameters
Exceptions
- exception - general exception of the
basic_jsonclass- 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
- array_t - type for arrays
- binary_t - type for binary arrays
- boolean_t - type for booleans
- default_object_comparator_t - default comparator for objects
- number_float_t - type for numbers (floating-point)
- number_integer_t - type for numbers (integer)
- number_unsigned_t - type for numbers (unsigned)
- object_comparator_t - comparator for objects
- object_t - type for objects
- string_t - type for strings
Parser callback
- parse_event_t - parser event types
- parser_callback_t - per-element parser callback type
Member functions
- (constructor)
- (destructor)
- operator= - copy assignment
- array (static) - explicitly create an array
- binary (static) - explicitly create a binary array
- object (static) - explicitly create an object
Object inspection
Functions to inspect the type of a JSON value.
- type - return the type of the JSON value
operator value_t- return the type of the JSON value- type_name - return the type as string
- is_primitive - return whether the type is primitive
- is_structured - return whether the type is structured
- is_null - return whether the value is null
- is_boolean - return whether the value is a boolean
- is_number - return whether the value is a number
- is_number_integer - return whether the value is an integer number
- is_number_unsigned - return whether the value is an unsigned integer number
- is_number_float - return whether the value is a floating-point number
- is_object - return whether the value is an object
- is_array - return whether the value is an array
- is_string - return whether the value is a string
- is_binary - return whether the value is a binary array
- is_discarded - return whether the value is discarded
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.
- get - get a value
- get_to - get a value and write it to a destination
- get_ptr - get a pointer value
- get_ref - get a reference value
operator ValueType- get a value- get_binary - get a binary value
- as_base_class - access the custom base class
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
- operator== - comparison: equal
- operator!= - comparison: not equal
- operator< - comparison: less than
- operator> - comparison: greater than
- operator<= - comparison: less than or equal
- operator>= - comparison: greater than or equal
- operator<=> - comparison: 3-way
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
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
- merge_patch - applies a JSON Merge Patch
- merge_diff (static) - creates a diff as a JSON Merge Patch
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
- operator<<(std::ostream&) - serialize to stream
- operator>>(std::istream&) - deserialize from stream
- to_string - user-defined
to_stringfunction for JSON values - format_as - user-defined
format_asfunction for JSON values (fmt support)
Literals
- operator""_json - user-defined string literal for JSON values
Helper classes
- std::formatter<basic_json> - make JSON values formattable with
std::format - std::hash<basic_json> - return a hash value for a JSON object
- std::swap<basic_json> - exchanges the values of two JSON objects
Examples
??? example
The example shows how the library is used.
```cpp
--8<-- "examples/README.cpp"
```
Output:
```json
--8<-- "examples/README.output"
```
See also
- RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format - specification of the JSON data interchange format
basic_json_document- /basic_json_view- parse a JSON text into a flat index and read it through a view- Zero-copy JSON views - when to use a document and a view instead of a
basic_json - Types - how JSON values are stored and which types exist
- Converting values - get values out of a JSON value and put values in
- Creating JSON values - all the ways to build a JSON value
- Arbitrary Type Conversions - convert your own types to and from JSON
Version history
- Added in version 1.0.0.