keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/end.md
.md
664
43
# <small>nlohmann::basic_json::</small>end ```cpp iterator end() noexcept; const_iterator end() const noexcept; ``` Returns an iterator to one past the last element. ![Illustration from cppreference.com](../../images/range-begin-end.svg) ## Return value iterator one past the last element ## Exception safety No-throw guarantee: this member function never throws exceptions. ## Complexity Constant. ## Examples ??? example The following code shows an example for `end()`. ```cpp --8<-- "examples/end.cpp" ``` Output: ```json --8<-- "examples/end.output" ``` ## Version history - Added in version 1.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/back.md
.md
1,324
66
# <small>nlohmann::basic_json::</small>back ```cpp reference back(); const_reference back() const; ``` Returns a reference to the last element in the container. For a JSON container `c`, the expression `c.back()` is equivalent to ```cpp auto tmp = c.end(); --tmp; return *tmp; ``` ## Return value In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, boolean, or binary values, a reference to the value is returned. ## Exception safety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. ## Exceptions If the JSON value is `#!json null`, exception [`invalid_iterator.214`](../../home/exceptions.md#jsonexceptioninvalid_iterator214) is thrown. ## Complexity Constant. ## Notes !!! info "Precondition" The array or object must not be empty. Calling `back` on an empty array or object yields undefined behavior. ## Examples ??? example The following code shows an example for `back()`. ```cpp --8<-- "examples/back.cpp" ``` Output: ```json --8<-- "examples/back.output" ``` ## See also - [front](front.md) to access the first element ## Version history - Added in version 1.0.0. - Adjusted code to return reference to binary values in version 3.8.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/operator_lt.md
.md
2,599
97
# <small>nlohmann::basic_json::</small>operator< ```cpp // until C++20 bool operator<(const_reference lhs, const_reference rhs) noexcept; // (1) template<typename ScalarType> bool operator<(const_reference lhs, const ScalarType rhs) noexcept; // (2) template<typename ScalarType> bool operator<(ScalarType lhs, const const_reference rhs) noexcept; // (2) ``` 1. Compares whether one JSON value `lhs` is less than another JSON value `rhs` according to the following rules: - If either operand is discarded, the comparison yields `#!cpp false`. - If both operands have the same type, the values are compared using their respective `operator<`. - Integer and floating-point numbers are automatically converted before comparison. - In case `lhs` and `rhs` have different types, the values are ignored and the order of the types is considered, which is: 1. null 2. boolean 3. number (all types) 4. object 5. array 6. string 7. binary For instance, any boolean value is considered less than any string. 2. Compares wether a JSON value is less than a scalar or a scalar is less than a JSON value by converting the scalar to a JSON value and comparing both JSON values according to 1. ## Template parameters `ScalarType` : a scalar type according to `std::is_scalar<ScalarType>::value` ## Parameters `lhs` (in) : first value to consider `rhs` (in) : second value to consider ## Return value whether `lhs` is less than `rhs` ## Exception safety No-throw guarantee: this function never throws exceptions. ## Complexity Linear. ## Notes !!! note "Comparing `NaN`" `NaN` values are unordered within the domain of numbers. The following comparisons all yield `#!cpp false`: 1. Comparing a `NaN` with itself. 2. Comparing a `NaN` with another `NaN`. 3. Comparing a `NaN` and any other number. !!! note "Operator overload resolution" Since C++20 overload resolution will consider the _rewritten candidate_ generated from [`operator<=>`](operator_spaceship.md). ## Examples ??? example The example demonstrates comparing several JSON types. ```cpp --8<-- "examples/operator__less.cpp" ``` Output: ```json --8<-- "examples/operator__less.output" ``` ## See also - [**operator<=>**](operator_spaceship.md) comparison: 3-way ## Version history 1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0. 2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/is_number.md
.md
1,303
57
# <small>nlohmann::basic_json::</small>is_number ```cpp constexpr bool is_number() const noexcept; ``` This function returns `#!cpp true` if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values. ## Return value `#!cpp true` if type is number (regardless whether integer, unsigned integer or floating-type), `#!cpp false` otherwise. ## Exception safety No-throw guarantee: this member function never throws exceptions. ## Complexity Constant. ## Possible implementation ```cpp constexpr bool is_number() const noexcept { return is_number_integer() || is_number_float(); } ``` ## Examples ??? example The following code exemplifies `is_number()` for all JSON types. ```cpp --8<-- "examples/is_number.cpp" ``` Output: ```json --8<-- "examples/is_number.output" ``` ## See also - [is_number_integer()](is_number_integer.md) check if value is an integer or unsigned integer number - [is_number_unsigned()](is_number_unsigned.md) check if value is an unsigned integer number - [is_number_float()](is_number_float.md) check if value is a floating-point number ## Version history - Added in version 1.0.0. - Extended to also return `#!cpp true` for unsigned integers in 2.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/is_discarded.md
.md
2,004
73
# <small>nlohmann::basic_json::</small>is_discarded ```cpp constexpr bool is_discarded() const noexcept; ``` This function returns `#!cpp true` for a JSON value if either: - the value was discarded during parsing with a callback function (see [`parser_callback_t`](parser_callback_t.md)), or - the value is the result of parsing invalid JSON with parameter `allow_exceptions` set to `#!cpp false`; see [`parse`](parse.md) for more information. ## Return value `#!cpp true` if type is discarded, `#!cpp false` otherwise. ## Exception safety No-throw guarantee: this member function never throws exceptions. ## Complexity Constant. ## Notes !!! note "Comparisons" Discarded values are never compared equal with [`operator==`](operator_eq.md). That is, checking whether a JSON value `j` is discarded will only work via: ```cpp j.is_discarded() ``` because ```cpp j == json::value_t::discarded ``` will always be `#!cpp false`. !!! note "Removal during parsing with callback functions" When a value is discarded by a callback function (see [`parser_callback_t`](parser_callback_t.md)) during parsing, then it is removed when it is part of a structured value. For instance, if the second value of an array is discarded, instead of `#!json [null, discarded, false]`, the array `#!json [null, false]` is returned. Only if the top-level value is discarded, the return value of the `parse` call is discarded. This function will always be `#!cpp false` for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases. ## Examples ??? example The following code exemplifies `is_discarded()` for all JSON types. ```cpp --8<-- "examples/is_discarded.cpp" ``` Output: ```json --8<-- "examples/is_discarded.output" ``` ## Version history - Added in version 1.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/binary_t.md
.md
3,559
90
# <small>nlohmann::basic_json::</small>binary_t ```cpp using binary_t = byte_container_with_subtype<BinaryType>; ``` This type is a type designed to carry binary data that appears in various serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and BSON's generic binary subtype. This type is NOT a part of standard JSON and exists solely for compatibility with these binary types. As such, it is simply defined as an ordered sequence of zero or more byte values. Additionally, as an implementation detail, the subtype of the binary data is carried around as a `std::uint64_t`, which is compatible with both of the binary data formats that use binary subtyping, (though the specific numbering is incompatible with each other, and it is up to the user to translate between them). The subtype is added to `BinaryType` via the helper type [byte_container_with_subtype](../byte_container_with_subtype/index.md). [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type as: > Major type 2: a byte string. The string's length in bytes is represented following the rules for positive integers > (major type 0). [MessagePack's documentation on the bin type family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family) describes this type as: > Bin format family stores a byte array in 2, 3, or 5 bytes of extra bytes in addition to the size of the byte array. [BSON's specifications](http://bsonspec.org/spec.html) describe several binary types; however, this type is intended to represent the generic binary type which has the description: > Generic binary subtype - This is the most commonly used binary subtype and should be the 'default' for drivers and > tools. None of these impose any limitations on the internal representation other than the basic unit of storage be some type of array whose parts are decomposable into bytes. The default representation of this binary format is a `#!cpp std::vector<std::uint8_t>`, which is a very common way to represent a byte array in modern C++. ## Template parameters `BinaryType` : container type to store arrays ## Notes #### Default type The default values for `BinaryType` is `#!cpp std::vector<std::uint8_t>`. #### Storage Binary Arrays are stored as pointers in a `basic_json` type. That is, for any access to array values, a pointer of the type `#!cpp binary_t*` must be dereferenced. #### Notes on subtypes - CBOR - Binary values are represented as byte strings. Subtypes are written as tags. - MessagePack - If a subtype is given and the binary array contains exactly 1, 2, 4, 8, or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8) is used. For other sizes, the ext family (ext8, ext16, ext32) is used. The subtype is then added as signed 8-bit integer. - If no subtype is given, the bin family (bin8, bin16, bin32) is used. - BSON - If a subtype is given, it is used and added as unsigned 8-bit integer. - If no subtype is given, the generic binary subtype 0x00 is used. ## Examples ??? example The following code shows that `binary_t` is by default, a typedef to `#!cpp nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>`. ```cpp --8<-- "examples/binary_t.cpp" ``` Output: ```json --8<-- "examples/binary_t.output" ``` ## See also - [byte_container_with_subtype](../byte_container_with_subtype/index.md) ## Version history - Added in version 3.8.0. Changed type of subtype to `std::uint64_t` in version 3.10.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/parser_callback_t.md
.md
3,648
74
# <small>nlohmann::basic_json::</small>parser_callback_t ```cpp template<typename BasicJsonType> using parser_callback_t = std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>; ``` With a parser callback function, the result of parsing a JSON text can be influenced. When passed to [`parse`](parse.md), it is called on certain events (passed as [`parse_event_t`](parse_event_t.md) via parameter `event`) with a set recursion depth `depth` and context JSON value `parsed`. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters `depth`, `event`, and `parsed`. | parameter `event` | description | parameter `depth` | parameter `parsed` | |-------------------------------|-----------------------------------------------------------|-------------------------------------------|----------------------------------| | `parse_event_t::object_start` | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded | | `parse_event_t::key` | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key | | `parse_event_t::object_end` | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object | | `parse_event_t::array_start` | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded | | `parse_event_t::array_end` | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array | | `parse_event_t::value` | the parser finished reading a JSON value | depth of the value | the parsed JSON value | ![Example when certain parse events are triggered](../../images/callback_events.png) Discarding a value (i.e., returning `#!cpp false`) has different effects depending on the context in which function was called: - Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read. - In case a value outside a structured type is skipped, it is replaced with `null`. This case happens if the top-level element is skipped. ## Parameters `depth` (in) : the depth of the recursion during parsing `event` (in) : an event of type [`parse_event_t`](parse_event_t.md) indicating the context in the callback function has been called `parsed` (in, out) : the current intermediate parse result; note that writing to this value has no effect for `parse_event_t::key` events ## Return value Whether the JSON value which called the function during parsing should be kept (`#!cpp true`) or not (`#!cpp false`). In the latter case, it is either skipped completely or replaced by an empty discarded object. ## Examples ??? example The example below demonstrates the `parse()` function with and without callback function. ```cpp --8<-- "examples/parse__string__parser_callback_t.cpp" ``` Output: ```json --8<-- "examples/parse__string__parser_callback_t.output" ``` ## Version history - Added in version 1.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/get_ptr.md
.md
1,531
61
# <small>nlohmann::basic_json::</small>get_ptr ```cpp template<typename PointerType> PointerType get_ptr() noexcept; template<typename PointerType> constexpr const PointerType get_ptr() const noexcept; ``` Implicit pointer access to the internally stored JSON value. No copies are made. ## Template parameters `PointerType` : pointer type; must be a pointer to [`array_t`](array_t.md), [`object_t`](object_t.md), [`string_t`](string_t.md), [`boolean_t`](boolean_t.md), [`number_integer_t`](number_integer_t.md), or [`number_unsigned_t`](number_unsigned_t.md), [`number_float_t`](number_float_t.md), or [`binary_t`](binary_t.md). Other types will not compile. ## Return value pointer to the internally stored JSON value if the requested pointer type fits to the JSON value; `#!cpp nullptr` otherwise ## Exception safety No-throw guarantee: this function never throws exceptions. ## Complexity Constant. ## Notes !!! danger "Undefined behavior" Writing data to the pointee of the result yields an undefined state. ## Examples ??? example The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `#!cpp nullptr` is returned if the value and the requested pointer type does not match. ```cpp --8<-- "examples/get_ptr.cpp" ``` Output: ```json --8<-- "examples/get_ptr.output" ``` ## Version history - Added in version 1.0.0. - Extended to binary types in version 3.8.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/from_bson.md
.md
3,479
111
# <small>nlohmann::basic_json::</small>from_bson ```cpp // (1) template<typename InputType> static basic_json from_bson(InputType&& i, const bool strict = true, const bool allow_exceptions = true); // (2) template<typename IteratorType> static basic_json from_bson(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true); ``` Deserializes a given input to a JSON value using the BSON (Binary JSON) serialization format. 1. Reads from a compatible input. 2. Reads from an iterator range. The exact mapping and its limitations is described on a [dedicated page](../../features/binary_formats/bson.md). ## Template parameters `InputType` : A compatible input, for instance: - an `std::istream` object - a `FILE` pointer - a C-style array of characters - a pointer to a null-terminated string of single byte characters - an object `obj` for which `begin(obj)` and `end(obj)` produces a valid pair of iterators. `IteratorType` : a compatible iterator type ## Parameters `i` (in) : an input in BSON format convertible to an input adapter `first` (in) : iterator to start of the input `last` (in) : iterator to end of the input `strict` (in) : whether to expect the input to be consumed until EOF (`#!cpp true` by default) `allow_exceptions` (in) : whether to throw exceptions in case of a parse error (optional, `#!cpp true` by default) ## Return value deserialized JSON value; in case of a parse error and `allow_exceptions` set to `#!cpp false`, the return value will be `value_t::discarded`. The latter can be checked with [`is_discarded`](is_discarded.md). ## Exception safety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. ## Exceptions Throws [`parse_error.114`](../../home/exceptions.md#jsonexceptionparse_error114) if an unsupported BSON record type is encountered. ## Complexity Linear in the size of the input. ## Examples ??? example The example shows the deserialization of a byte vector in BSON format to a JSON value. ```cpp --8<-- "examples/from_bson.cpp" ``` Output: ```json --8<-- "examples/from_bson.output" ``` ## See also - [BSON specification](http://bsonspec.org/spec.html) - [to_bson](to_bson.md) for the analogous serialization - [from_cbor](from_cbor.md) for the related CBOR format - [from_msgpack](from_msgpack.md) for the related MessagePack format - [from_ubjson](from_ubjson.md) for the related UBJSON format ## Version history - Added in version 3.4.0. !!! warning "Deprecation" - Overload (2) replaces calls to `from_bson` with a pointer and a length as first two parameters, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like `#!cpp from_bson(ptr, len, ...);` with `#!cpp from_bson(ptr, ptr+len, ...);`. - Overload (2) replaces calls to `from_bson` with a pair of iterators as their first parameter, which has been deprecated in version 3.8.0. This overload will be removed in version 4.0.0. Please replace all calls like `#!cpp from_bson({ptr, ptr+len}, ...);` with `#!cpp from_bson(ptr, ptr+len, ...);`. You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated function.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/items.md
.md
2,696
101
# <small>nlohmann::basic_json::</small>items ```cpp iteration_proxy<iterator> items() noexcept; iteration_proxy<const_iterator> items() const noexcept; ``` This function allows accessing `iterator::key()` and `iterator::value()` during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator. For loop without `items()` function: ```cpp for (auto it = j_object.begin(); it != j_object.end(); ++it) { std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; } ``` Range-based for loop without `items()` function: ```cpp for (auto it : j_object) { // "it" is of type json::reference and has no key() member std::cout << "value: " << it << '\n'; } ``` Range-based for loop with `items()` function: ```cpp for (auto& el : j_object.items()) { std::cout << "key: " << el.key() << ", value:" << el.value() << '\n'; } ``` The `items()` function also allows using [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding) (C++17): ```cpp for (auto& [key, val] : j_object.items()) { std::cout << "key: " << key << ", value:" << val << '\n'; } ``` ## Return value iteration proxy object wrapping the current value with an interface to use in range-based for loops ## Exception safety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. ## Complexity Constant. ## Notes When iterating over an array, `key()` will return the index of the element as string (see example). For primitive types (e.g., numbers), `key()` returns an empty string. !!! danger "Lifetime issues" Using `items()` on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See <https://github.com/nlohmann/json/issues/2040> for more information. ## Examples ??? example The following code shows an example for `items()`. ```cpp --8<-- "examples/items.cpp" ``` Output: ```json --8<-- "examples/items.output" ``` ## Version history - Added `iterator_wrapper` in version 3.0.0. - Added `items` and deprecated `iterator_wrapper` in version 3.1.0. - Added structured binding support in version 3.5.0. !!! warning "Deprecation" This function replaces the static function `iterator_wrapper` which was introduced in version 1.0.0, but has been deprecated in version 3.1.0. Function `iterator_wrapper` will be removed in version 4.0.0. Please replace all occurrences of `#!cpp iterator_wrapper(j)` with `#!cpp j.items()`. You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated function.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/binary.md
.md
1,899
67
# <small>nlohmann::basic_json::</small>binary ```cpp // (1) static basic_json binary(const typename binary_t::container_type& init); static basic_json binary(typename binary_t::container_type&& init); // (2) static basic_json binary(const typename binary_t::container_type& init, std::uint8_t subtype); static basic_json binary(typename binary_t::container_type&& init, std::uint8_t subtype); ``` 1. Creates a JSON binary array value from a given binary container. 2. Creates a JSON binary array value from a given binary container with subtype. Binary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to create a value for serialization to those formats. ## Parameters `init` (in) : container containing bytes to use as binary type `subtype` (in) : subtype to use in CBOR, MessagePack, and BSON ## Return value JSON binary array value ## Exception safety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. ## Complexity Linear in the size of `init`; constant for `typename binary_t::container_type&& init` versions. ## Notes Note, this function exists because of the difficulty in correctly specifying the correct template overload in the standard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a `std::vector`. Because JSON binary arrays are a non-standard extension it was decided that it would be best to prevent automatic initialization of a binary array type, for backwards compatibility and so it does not happen on accident. ## Examples ??? example The following code shows how to create a binary value. ```cpp --8<-- "examples/binary.cpp" ``` Output: ```json --8<-- "examples/binary.output" ``` ## Version history - Added in version 3.8.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/operator=.md
.md
1,056
44
# <small>nlohmann::basic_json::</small>operator= ```cpp basic_json& operator=(basic_json other) noexcept ( std::is_nothrow_move_constructible<value_t>::value && std::is_nothrow_move_assignable<value_t>::value && std::is_nothrow_move_constructible<json_value>::value && std::is_nothrow_move_assignable<json_value>::value ); ``` Copy assignment operator. Copies a JSON value via the "copy and swap" strategy: It is expressed in terms of the copy constructor, destructor, and the `swap()` member function. ## Parameters `other` (in) : value to copy from ## Complexity Linear. ## Examples ??? example The code below shows and example for the copy assignment. It creates a copy of value `a` which is then swapped with `b`. Finally, the copy of `a` (which is the null value after the swap) is destroyed. ```cpp --8<-- "examples/basic_json__copyassignment.cpp" ``` Output: ```json --8<-- "examples/basic_json__copyassignment.output" ``` ## Version history - Added in version 1.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/get_to.md
.md
1,518
59
# <small>nlohmann::basic_json::</small>get_to ```cpp template<typename ValueType> ValueType& get_to(ValueType& v) const noexcept( noexcept(JSONSerializer<ValueType>::from_json( std::declval<const basic_json_t&>(), v))); ``` Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the `json_serializer<ValueType>` `from_json()` method. The function is equivalent to executing ```cpp ValueType v; JSONSerializer<ValueType>::from_json(*this, v); ``` This overload is chosen if: - `ValueType` is not `basic_json`, - `json_serializer<ValueType>` has a `from_json()` method of the form `void from_json(const basic_json&, ValueType&)` ## Template parameters `ValueType` : the value type to return ## Return value the input parameter, allowing chaining calls ## Exceptions Depends on what `json_serializer<ValueType>` `from_json()` method throws ## Examples ??? example The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers, (2) A JSON array can be converted to a standard `#!cpp std::vector<short>`, (3) A JSON object can be converted to C++ associative containers such as `#cpp std::unordered_map<std::string, json>`. ```cpp --8<-- "examples/get_to.cpp" ``` Output: ```json --8<-- "examples/get_to.output" ``` ## Version history - Since version 3.3.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/unflatten.md
.md
1,606
62
# <small>nlohmann::basic_json::</small>unflatten ```cpp basic_json unflatten() const; ``` The function restores the arbitrary nesting of a JSON value that has been flattened before using the [`flatten()`](flatten.md) function. The JSON value must meet certain constraints: 1. The value must be an object. 2. The keys must be JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) 3. The mapped values must be primitive JSON types. ## Return value the original JSON from a flattened version ## Exception safety Strong exception safety: if an exception occurs, the original value stays intact. ## Exceptions The function can throw the following exceptions: - Throws [`type_error.314`](../../home/exceptions.md#jsonexceptiontype_error314) if value is not an object - Throws [`type_error.315`](../../home/exceptions.md#jsonexceptiontype_error315) if object values are not primitive ## Complexity Linear in the size the JSON value. ## Notes Empty objects and arrays are flattened by [`flatten()`](flatten.md) to `#!json null` values and can not unflattened to their original type. Apart from this example, for a JSON value `j`, the following is always true: `#!cpp j == j.flatten().unflatten()`. ## Examples ??? example The following code shows how a flattened JSON object is unflattened into the original nested JSON object. ```cpp --8<-- "examples/unflatten.cpp" ``` Output: ```json --8<-- "examples/unflatten.output" ``` ## See also - [flatten](flatten.md) the reverse function ## Version history - Added in version 2.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/type_error.md
.md
1,707
69
# <small>nlohmann::basic_json::</small>type_error ```cpp class type_error : public exception; ``` This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics. Exceptions have ids 3xx (see [list of type errors](../../home/exceptions.md#type-errors)). ```plantuml std::exception <|-- basic_json::exception basic_json::exception <|-- basic_json::parse_error basic_json::exception <|-- basic_json::invalid_iterator basic_json::exception <|-- basic_json::type_error basic_json::exception <|-- basic_json::out_of_range basic_json::exception <|-- basic_json::other_error interface std::exception {} class basic_json::exception { + const int id + const char* what() const } class basic_json::parse_error { + const std::size_t byte } class basic_json::type_error #FFFF00 {} ``` ## Member functions - **what** - returns explanatory string ## Member variables - **id** - the id of the exception ## Examples ??? example The following code shows how a `type_error` exception can be caught. ```cpp --8<-- "examples/type_error.cpp" ``` Output: ```json --8<-- "examples/type_error.output" ``` ## See also - [List of type errors](../../home/exceptions.md#type-errors) - [`parse_error`](parse_error.md) for exceptions indicating a parse error - [`invalid_iterator`](invalid_iterator.md) for exceptions indicating errors with iterators - [`out_of_range`](out_of_range.md) for exceptions indicating access out of the defined range - [`other_error`](other_error.md) for exceptions indicating other library errors ## Version history - Since version 3.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/push_back.md
.md
3,005
107
# <small>nlohmann::basic_json::</small>push_back ```cpp // (1) void push_back(basic_json&& val); void push_back(const basic_json& val); // (2) void push_back(const typename object_t::value_type& val); // (3) void push_back(initializer_list_t init); ``` 1. Appends the given element `val` to the end of the JSON array. If the function is called on a JSON null value, an empty array is created before appending `val`. 2. Inserts the given element `val` to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting `val`. 3. This function allows using `push_back` with an initializer list. In case 1. the current value is an object, 2. the initializer list `init` contains only two elements, and 3. the first element of `init` is a string, `init` is converted into an object element and added using `push_back(const typename object_t::value_type&)`. Otherwise, `init` is converted to a JSON value and added using `push_back(basic_json&&)`. ## Parameters `val` (in) : the value to add to the JSON array/object `init` (in) : an initializer list ## Exceptions All functions can throw the following exception: - Throws [`type_error.308`](../../home/exceptions.md#jsonexceptiontype_error308) when called on a type other than JSON array or null; example: `"cannot use push_back() with number"` ## Complexity 1. Amortized constant. 2. Logarithmic in the size of the container, O(log(`size()`)). 3. Linear in the size of the initializer list `init`. ## Notes (3) This function is required to resolve an ambiguous overload error, because pairs like `{"key", "value"}` can be both interpreted as `object_t::value_type` or `std::initializer_list<basic_json>`, see [#235](https://github.com/nlohmann/json/issues/235) for more information. ## Examples ??? example "Example: (1) add element to array" The example shows how `push_back()` and `+=` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array. ```cpp --8<-- "examples/push_back.cpp" ``` Output: ```json --8<-- "examples/push_back.output" ``` ??? example "Example: (2) add element to object" The example shows how `push_back()` and `+=` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object. ```cpp --8<-- "examples/push_back__object_t__value.cpp" ``` Output: ```json --8<-- "examples/push_back__object_t__value.output" ``` ??? example "Example: (3) add to object from initializer list" The example shows how initializer lists are treated as objects when possible. ```cpp --8<-- "examples/push_back__initializer_list.cpp" ``` Output: ```json --8<-- "examples/push_back__initializer_list.output" ``` ## Version history 1. Since version 1.0.0. 2. Since version 1.0.0. 2. Since version 2.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/get_ref.md
.md
1,678
65
# <small>nlohmann::basic_json::</small>get_ref ```cpp template<typename ReferenceType> ReferenceType get_ref(); template<typename ReferenceType> const ReferenceType get_ref() const; ``` Implicit reference access to the internally stored JSON value. No copies are made. ## Template parameters `ReferenceType` : reference type; must be a reference to [`array_t`](array_t.md), [`object_t`](object_t.md), [`string_t`](string_t.md), [`boolean_t`](boolean_t.md), [`number_integer_t`](number_integer_t.md), or [`number_unsigned_t`](number_unsigned_t.md), [`number_float_t`](number_float_t.md), or [`binary_t`](binary_t.md). Enforced by a static assertion. ## Return value reference to the internally stored JSON value if the requested reference type fits to the JSON value; throws [`type_error.303`](../../home/exceptions.md#jsonexceptiontype_error303) otherwise ## Exception safety Strong exception safety: if an exception occurs, the original value stays intact. ## Exceptions Throws [`type_error.303`](../../home/exceptions.md#jsonexceptiontype_error303) if the requested reference type does not match the stored JSON value type; example: `"incompatible ReferenceType for get_ref, actual type is binary"`. ## Complexity Constant. ## Notes !!! danger "Undefined behavior" Writing data to the referee of the result yields an undefined state. ## Examples ??? example The example shows several calls to `get_ref()`. ```cpp --8<-- "examples/get_ref.cpp" ``` Output: ```json --8<-- "examples/get_ref.output" ``` ## Version history - Added in version 1.1.0. - Extended to binary types in version 3.8.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/operator_ne.md
.md
2,545
99
# <small>nlohmann::basic_json::</small>operator!= ```cpp // until C++20 bool operator!=(const_reference lhs, const_reference rhs) noexcept; // (1) template<typename ScalarType> bool operator!=(const_reference lhs, const ScalarType rhs) noexcept; // (2) template<typename ScalarType> bool operator!=(ScalarType lhs, const const_reference rhs) noexcept; // (2) // since C++20 class basic_json { bool operator!=(const_reference rhs) const noexcept; // (1) template<typename ScalarType> bool operator!=(ScalarType rhs) const noexcept; // (2) }; ``` 1. Compares two JSON values for inequality according to the following rules: - The comparison always yields `#!cpp false` if (1) either operand is discarded, or (2) either operand is `NaN` and the other operand is either `NaN` or any other number. - Otherwise, returns the result of `#!cpp !(lhs == rhs)` (until C++20) or `#!cpp !(*this == rhs)` (since C++20). 2. Compares a JSON value and a scalar or a scalar and a JSON value for inequality by converting the scalar to a JSON value and comparing both JSON values according to 1. ## Template parameters `ScalarType` : a scalar type according to `std::is_scalar<ScalarType>::value` ## Parameters `lhs` (in) : first value to consider `rhs` (in) : second value to consider ## Return value whether the values `lhs`/`*this` and `rhs` are not equal ## Exception safety No-throw guarantee: this function never throws exceptions. ## Complexity Linear. ## Notes !!! note "Comparing `NaN`" `NaN` values are unordered within the domain of numbers. The following comparisons all yield `#!cpp false`: 1. Comparing a `NaN` with itself. 2. Comparing a `NaN` with another `NaN`. 3. Comparing a `NaN` and any other number. ## Examples ??? example The example demonstrates comparing several JSON types. ```cpp --8<-- "examples/operator__notequal.cpp" ``` Output: ```json --8<-- "examples/operator__notequal.output" ``` ??? example The example demonstrates comparing several JSON types against the null pointer (JSON `#!json null`). ```cpp --8<-- "examples/operator__notequal__nullptr_t.cpp" ``` Output: ```json --8<-- "examples/operator__notequal__nullptr_t.output" ``` ## Version history 1. Added in version 1.0.0. Added C++20 member functions in version 3.11.0. 2. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/cbor_tag_handler_t.md
.md
842
43
# <small>nlohmann::basic_json::</small>cbor_tag_handler_t ```cpp enum class cbor_tag_handler_t { error, ignore, store }; ``` This enumeration is used in the [`from_cbor`](from_cbor.md) function to choose how to treat tags: error : throw a `parse_error` exception in case of a tag ignore : ignore tags store : store tagged values as binary container with subtype (for bytes 0xd8..0xdb) ## Examples ??? example The example below shows how the different values of the `cbor_tag_handler_t` influence the behavior of [`from_cbor`](from_cbor.md) when reading a tagged byte string. ```cpp --8<-- "examples/cbor_tag_handler_t.cpp" ``` Output: ```json --8<-- "examples/cbor_tag_handler_t.output" ``` ## Version history - Added in version 3.9.0. Added value `store` in 3.10.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/diff.md
.md
1,265
63
# <small>nlohmann::basic_json::</small>diff ```cpp static basic_json diff(const basic_json& source, const basic_json& target); ``` Creates a [JSON Patch](http://jsonpatch.com) so that value `source` can be changed into the value `target` by calling [`patch`](patch.md) function. For two JSON values `source` and `target`, the following code yields always `#!cpp true`: ```cpp source.patch(diff(source, target)) == target; ``` ## Parameters `source` (in) : JSON value to compare from `target` (in) : JSON value to compare against ## Return value a JSON patch to convert the `source` to `target` ## Exception safety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. ## Complexity Linear in the lengths of `source` and `target`. ## Notes Currently, only `remove`, `add`, and `replace` operations are generated. ## Examples ??? example The following code shows how a JSON patch is created as a diff for two JSON values. ```cpp --8<-- "examples/diff.cpp" ``` Output: ```json --8<-- "examples/diff.output" ``` ## See also - [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) ## Version history - Added in version 2.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/contains.md
.md
3,270
119
# <small>nlohmann::basic_json::</small>contains ```cpp // (1) bool contains(const typename object_t::key_type& key) const; // (2) template<typename KeyType> bool contains(KeyType&& key) const; // (3) bool contains(const json_pointer& ptr) const; ``` 1. Check whether an element exists in a JSON object with a key equivalent to `key`. If the element is not found or the JSON value is not an object, `#!cpp false` is returned. 2. See 1. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and `#!cpp typename object_comparator_t::is_transparent` denotes a type. 3. Check whether the given JSON pointer `ptr` can be resolved in the current JSON value. ## Template parameters `KeyType` : A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with [`string_t`](string_t.md) using [`object_comparator_t`](object_comparator_t.md). This can also be a string view (C++17). ## Parameters `key` (in) : key value to check its existence. `ptr` (in) : JSON pointer to check its existence. ## Return value 1. `#!cpp true` if an element with specified `key` exists. If no such element with such key is found or the JSON value is not an object, `#!cpp false` is returned. 2. See 1. 3. `#!cpp true` if the JSON pointer can be resolved to a stored value, `#!cpp false` otherwise. ## Exception safety Strong exception safety: if an exception occurs, the original value stays intact. ## Exceptions 1. The function does not throw exceptions. 2. The function does not throw exceptions. 3. The function can throw the following exceptions: - Throws [`parse_error.106`](../../home/exceptions.md#jsonexceptionparse_error106) if an array index begins with `0`. - Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) if an array index was not a number. ## Complexity Logarithmic in the size of the JSON object. ## Notes - This method always returns `#!cpp false` when executed on a JSON type that is not an object. - This method can be executed on any JSON value type. !!! info "Postconditions" If `#!cpp j.contains(x)` returns `#!c true` for a key or JSON pointer `x`, then it is safe to call `j[x]`. ## Examples ??? example "Example: (1) check with key" The example shows how `contains()` is used. ```cpp --8<-- "examples/contains__object_t_key_type.cpp" ``` Output: ```json --8<-- "examples/contains__object_t_key_type.output" ``` ??? example "Example: (2) check with key using string_view" The example shows how `contains()` is used. ```cpp --8<-- "examples/contains__keytype.c++17.cpp" ``` Output: ```json --8<-- "examples/contains__keytype.c++17.output" ``` ??? example "Example: (3) check with JSON pointer" The example shows how `contains()` is used. ```cpp --8<-- "examples/contains__json_pointer.cpp" ``` Output: ```json --8<-- "examples/contains__json_pointer.output" ``` ## Version history 1. Added in version 3.11.0. 2. Added in version 3.6.0. Extended template `KeyType` to support comparable types in version 3.11.0. 3. Added in version 3.7.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/crbegin.md
.md
695
42
# <small>nlohmann::basic_json::</small>crbegin ```cpp const_reverse_iterator crbegin() const noexcept; ``` Returns an iterator to the reverse-beginning; that is, the last element. ![Illustration from cppreference.com](../../images/range-rbegin-rend.svg) ## Return value reverse iterator to the first element ## Exception safety No-throw guarantee: this member function never throws exceptions. ## Complexity Constant. ## Examples ??? example The following code shows an example for `crbegin()`. ```cpp --8<-- "examples/crbegin.cpp" ``` Output: ```json --8<-- "examples/crbegin.output" ``` ## Version history - Added in version 1.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/flatten.md
.md
1,164
51
# <small>nlohmann::basic_json::</small>flatten ```cpp basic_json flatten() const; ``` The function creates a JSON object whose keys are JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all primitive (see [`is_primitive()`](is_primitive.md) for more information). The original JSON value can be restored using the [`unflatten()`](unflatten.md) function. ## Return value an object that maps JSON pointers to primitive values ## Exception safety Strong exception safety: if an exception occurs, the original value stays intact. ## Complexity Linear in the size the JSON value. ## Notes Empty objects and arrays are flattened to `#!json null` and will not be reconstructed correctly by the [`unflatten()`](unflatten.md) function. ## Examples ??? example The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers. ```cpp --8<-- "examples/flatten.cpp" ``` Output: ```json --8<-- "examples/flatten.output" ``` ## See also - [unflatten](unflatten.md) the reverse function ## Version history - Added in version 2.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/~basic_json.md
.md
329
22
# <small>nlohmann::basic_json::</small>~basic_json ```cpp ~basic_json() noexcept; ``` Destroys the JSON value and frees all allocated memory. ## Exception safety No-throw guarantee: this member function never throws exceptions. ## Complexity Linear. <!-- NOLINT Examples --> ## Version history - Added in version 1.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/basic_json.md
.md
15,491
403
# <small>nlohmann::basic_json::</small>basic_json ```cpp // (1) basic_json(const value_t v); // (2) basic_json(std::nullptr_t = nullptr) noexcept; // (3) template<typename CompatibleType> basic_json(CompatibleType&& val) noexcept(noexcept( JSONSerializer<U>::to_json(std::declval<basic_json_t&>(), std::forward<CompatibleType>(val)))); // (4) template<typename BasicJsonType> basic_json(const BasicJsonType& val); // (5) basic_json(initializer_list_t init, bool type_deduction = true, value_t manual_type = value_t::array); // (6) basic_json(size_type cnt, const basic_json& val); // (7) basic_json(iterator first, iterator last); basic_json(const_iterator first, const_iterator last); // (8) basic_json(const basic_json& other); // (9) basic_json(basic_json&& other) noexcept; ``` 1. Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type: | Value type | initial value | |------------|----------------| | null | `#!json null` | | boolean | `#!json false` | | string | `#!json ""` | | number | `#!json 0` | | object | `#!json {}` | | array | `#!json []` | | binary | empty array | The postcondition of this constructor can be restored by calling [`clear()`](clear.md). 2. Create a `#!json null` JSON value. It either takes a null pointer as parameter (explicitly creating `#!json null`) or no parameter (implicitly creating `#!json null`). The passed null pointer itself is not read -- it is only used to choose the right constructor. 3. This is a "catch all" constructor for all compatible JSON types; that is, types for which a `to_json()` method exists. The constructor forwards the parameter `val` to that method (to `json_serializer<U>::to_json` method with `U = uncvref_t<CompatibleType>`, to be exact). Template type `CompatibleType` includes, but is not limited to, the following types: - **arrays**: [`array_t`](array_t.md) and all kinds of compatible containers such as `std::vector`, `std::deque`, `std::list`, `std::forward_list`, `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, `std::multiset`, and `std::unordered_multiset` with a `value_type` from which a `basic_json` value can be constructed. - **objects**: [`object_t`](object_t.md) and all kinds of compatible associative containers such as `std::map`, `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with a `key_type` compatible to `string_t` and a `value_type` from which a `basic_json` value can be constructed. - **strings**: `string_t`, string literals, and all compatible string containers can be used. - **numbers**: [`number_integer_t`](number_integer_t.md), [`number_unsigned_t`](number_unsigned_t.md), [`number_float_t`](number_float_t.md), and all convertible number types such as `int`, `size_t`, `int64_t`, `float` or `double` can be used. - **boolean**: `boolean_t` / `bool` can be used. - **binary**: `binary_t` / `std::vector<uint8_t>` may be used; unfortunately because string literals cannot be distinguished from binary character arrays by the C++ type system, all types compatible with `const char*` will be directed to the string constructor instead. This is both for backwards compatibility, and due to the fact that a binary type is not a standard JSON type. See the examples below. 4. This is a constructor for existing `basic_json` types. It does not hijack copy/move constructors, since the parameter has different template arguments than the current ones. The constructor tries to convert the internal `m_value` of the parameter. 5. Creates a JSON value of type array or object from the passed initializer list `init`. In case `type_deduction` is `#!cpp true` (default), the type of the JSON value to be created is deducted from the initializer list `init` according to the following rules: 1. If the list is empty, an empty JSON object value `{}` is created. 2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values. 3. In all other cases, an array is created. The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows: 1. The empty initializer list is written as `#!cpp {}` which is exactly an empty JSON object. 2. C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object. 3. In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe. With the rules described above, the following JSON values cannot be expressed by an initializer list: - the empty array (`#!json []`): use `array(initializer_list_t)` with an empty initializer list in this case - arrays whose elements satisfy rule 2: use `array(initializer_list_t)` with the same initializer list in this case Function [`array()`](array.md) and [`object()`](object.md) force array and object creation from initializer lists, respectively. 6. Constructs a JSON array value by creating `cnt` copies of a passed value. In case `cnt` is `0`, an empty array is created. 7. Constructs the JSON value with the contents of the range `[first, last)`. The semantics depends on the different types a JSON value can have: - In case of a `#!json null` type, [invalid_iterator.206](../../home/exceptions.md#jsonexceptioninvalid_iterator206) is thrown. - In case of other primitive types (number, boolean, or string), `first` must be `begin()` and `last` must be `end()`. In this case, the value is copied. Otherwise, [`invalid_iterator.204`](../../home/exceptions.md#jsonexceptioninvalid_iterator204) is thrown. - In case of structured types (array, object), the constructor behaves as similar versions for `std::vector` or `std::map`; that is, a JSON array or object is constructed from the values in the range. 8. Creates a copy of a given JSON value. 9. Move constructor. Constructs a JSON value with the contents of the given value `other` using move semantics. It "steals" the resources from `other` and leaves it as JSON `#!json null` value. ## Template parameters `CompatibleType` : a type such that: - `CompatibleType` is not derived from `std::istream`, - `CompatibleType` is not `basic_json` (to avoid hijacking copy/move constructors), - `CompatibleType` is not a different `basic_json` type (i.e. with different template arguments) - `CompatibleType` is not a `basic_json` nested type (e.g., `json_pointer`, `iterator`, etc.) - `json_serializer<U>` (with `U = uncvref_t<CompatibleType>`) has a `to_json(basic_json_t&, CompatibleType&&)` method `BasicJsonType`: : a type such that: - `BasicJsonType` is a `basic_json` type. - `BasicJsonType` has different template arguments than `basic_json_t`. `U`: : `uncvref_t<CompatibleType>` ## Parameters `v` (in) : the type of the value to create `val` (in) : the value to be forwarded to the respective constructor `init` (in) : initializer list with JSON values `type_deduction` (in) : internal parameter; when set to `#!cpp true`, the type of the JSON value is deducted from the initializer list `init`; when set to `#!cpp false`, the type provided via `manual_type` is forced. This mode is used by the functions `array(initializer_list_t)` and `object(initializer_list_t)`. `manual_type` (in) : internal parameter; when `type_deduction` is set to `#!cpp false`, the created JSON value will use the provided type (only `value_t::array` and `value_t::object` are valid); when `type_deduction` is set to `#!cpp true`, this parameter has no effect `cnt` (in) : the number of JSON copies of `val` to create `first` (in) : begin of the range to copy from (included) `last` (in) : end of the range to copy from (excluded) `other` (in) : the JSON value to copy/move ## Exception safety 1. Strong guarantee: if an exception is thrown, there are no changes to any JSON value. 2. No-throw guarantee: this constructor never throws exceptions. 3. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value. 4. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value. 5. Strong guarantee: if an exception is thrown, there are no changes to any JSON value. 6. Strong guarantee: if an exception is thrown, there are no changes to any JSON value. 7. Strong guarantee: if an exception is thrown, there are no changes to any JSON value. 8. Strong guarantee: if an exception is thrown, there are no changes to any JSON value. 9. No-throw guarantee: this constructor never throws exceptions. ## Exceptions 1. (none) 2. The function does not throw exceptions. 3. (none) 4. (none) 5. The function can throw the following exceptions: - Throws [`type_error.301`](../../home/exceptions.md#jsonexceptiontype_error301) if `type_deduction` is `#!cpp false`, `manual_type` is `value_t::object`, but `init` contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If `type_deduction` would have been `#!cpp true`, an array would have been created. See `object(initializer_list_t)` for an example. 6. (none) 7. The function can throw the following exceptions: - Throws [`invalid_iterator.201`](../../home/exceptions.md#jsonexceptioninvalid_iterator201) if iterators `first` and `last` are not compatible (i.e., do not belong to the same JSON value). In this case, the range `[first, last)` is undefined. - Throws [`invalid_iterator.204`](../../home/exceptions.md#jsonexceptioninvalid_iterator204) if iterators `first` and `last` belong to a primitive type (number, boolean, or string), but `first` does not point to the first element anymore. In this case, the range `[first, last)` is undefined. See example code below. - Throws [`invalid_iterator.206`](../../home/exceptions.md#jsonexceptioninvalid_iterator206) if iterators `first` and `last` belong to a `#!json null` value. In this case, the range `[first, last)` is undefined. 8. (none) 9. The function does not throw exceptions. ## Complexity 1. Constant. 2. Constant. 3. Usually linear in the size of the passed `val`, also depending on the implementation of the called `to_json()` method. 4. Usually linear in the size of the passed `val`, also depending on the implementation of the called `to_json()` method. 5. Linear in the size of the initializer list `init`. 6. Linear in `cnt`. 7. Linear in distance between `first` and `last`. 8. Linear in the size of `other`. 9. Constant. ## Notes - Overload 5: !!! note "Empty initializer list" When used without parentheses around an empty initializer list, `basic_json()` is called instead of this function, yielding the JSON `#!json null` value. - Overload 7: !!! info "Preconditions" - Iterators `first` and `last` must be initialized. **This precondition is enforced with a [runtime assertion](../../features/assertions.md). - Range `[first, last)` is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions above. A violation of this precondition yields undefined behavior. !!! danger "Runtime assertion" A precondition is enforced with a [runtime assertion](../../features/assertions.md). - Overload 8: !!! info "Postcondition" `#!cpp *this == other` - Overload 9: !!! info "Postconditions" - `#!cpp `*this` has the same value as `other` before the call. - `other` is a JSON `#!json null` value ## Examples ??? example "Example: (1) create an empty value with a given type" The following code shows the constructor for different `value_t` values. ```cpp --8<-- "examples/basic_json__value_t.cpp" ``` Output: ```json --8<-- "examples/basic_json__value_t.output" ``` ??? example "Example: (2) create a `#!json null` object" The following code shows the constructor with and without a null pointer parameter. ```cpp --8<-- "examples/basic_json__nullptr_t.cpp" ``` Output: ```json --8<-- "examples/basic_json__nullptr_t.output" ``` ??? example "Example: (3) create a JSON value from compatible types" The following code shows the constructor with several compatible types. ```cpp --8<-- "examples/basic_json__CompatibleType.cpp" ``` Output: ```json --8<-- "examples/basic_json__CompatibleType.output" ``` Note the output is platform-dependent. ??? example "Example: (5) create a container (array or object) from an initializer list" The example below shows how JSON values are created from initializer lists. ```cpp --8<-- "examples/basic_json__list_init_t.cpp" ``` Output: ```json --8<-- "examples/basic_json__list_init_t.output" ``` ??? example "Example: (6) construct an array with count copies of given value" The following code shows examples for creating arrays with several copies of a given value. ```cpp --8<-- "examples/basic_json__size_type_basic_json.cpp" ``` Output: ```json --8<-- "examples/basic_json__size_type_basic_json.output" ``` ??? example "Example: (7) construct a JSON container given an iterator range" The example below shows several ways to create JSON values by specifying a subrange with iterators. ```cpp --8<-- "examples/basic_json__InputIt_InputIt.cpp" ``` Output: ```json --8<-- "examples/basic_json__InputIt_InputIt.output" ``` ??? example "Example: (8) copy constructor" The following code shows an example for the copy constructor. ```cpp --8<-- "examples/basic_json__basic_json.cpp" ``` Output: ```json --8<-- "examples/basic_json__basic_json.output" ``` ??? example "Example: (9) move constructor" The code below shows the move constructor explicitly called via `std::move`. ```cpp --8<-- "examples/basic_json__moveconstructor.cpp" ``` Output: ```json --8<-- "examples/basic_json__moveconstructor.output" ``` ## Version history 1. Since version 1.0.0. 2. Since version 1.0.0. 3. Since version 2.1.0. 4. Since version 3.2.0. 5. Since version 1.0.0. 6. Since version 1.0.0. 7. Since version 1.0.0. 8. Since version 1.0.0. 9. Since version 1.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/clear.md
.md
1,256
59
# <small>nlohmann::basic_json::</small>clear ```cpp void clear() noexcept; ``` Clears the content of a JSON value and resets it to the default value as if [`basic_json(value_t)`](basic_json.md) would have been called with the current value type from [`type()`](type.md): | Value type | initial value | |------------|----------------------| | null | `null` | | boolean | `false` | | string | `""` | | number | `0` | | binary | An empty byte vector | | object | `{}` | | array | `[]` | Has the same effect as calling ```.cpp *this = basic_json(type()); ``` ## Exception safety No-throw guarantee: this function never throws exceptions. ## Complexity Linear in the size of the JSON value. ## Notes All iterators, pointers and references related to this container are invalidated. ## Examples ??? example The example below shows the effect of `clear()` to different JSON types. ```cpp --8<-- "examples/clear.cpp" ``` Output: ```json --8<-- "examples/clear.output" ``` ## Version history - Added in version 1.0.0. - Added support for binary types in version 3.8.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/is_object.md
.md
664
40
# <small>nlohmann::basic_json::</small>is_object ```cpp constexpr bool is_object() const noexcept; ``` This function returns `#!cpp true` if and only if the JSON value is an object. ## Return value `#!cpp true` if type is an object, `#!cpp false` otherwise. ## Exception safety No-throw guarantee: this member function never throws exceptions. ## Complexity Constant. ## Examples ??? example The following code exemplifies `is_object()` for all JSON types. ```cpp --8<-- "examples/is_object.cpp" ``` Output: ```json --8<-- "examples/is_object.output" ``` ## Version history - Added in version 1.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/exception.md
.md
2,098
76
# <small>nlohmann::basic_json::</small>exception ```cpp class exception : public std::exception; ``` This class is an extension of [`std::exception`](https://en.cppreference.com/w/cpp/error/exception) objects with a member `id` for exception ids. It is used as the base class for all exceptions thrown by the `basic_json` class. This class can hence be used as "wildcard" to catch exceptions, see example below. ```plantuml std::exception <|-- basic_json::exception basic_json::exception <|-- basic_json::parse_error basic_json::exception <|-- basic_json::invalid_iterator basic_json::exception <|-- basic_json::type_error basic_json::exception <|-- basic_json::out_of_range basic_json::exception <|-- basic_json::other_error interface std::exception {} class basic_json::exception #FFFF00 { + const int id + const char* what() const } class basic_json::parse_error { + const std::size_t byte } ``` Subclasses: - [`parse_error`](parse_error.md) for exceptions indicating a parse error - [`invalid_iterator`](invalid_iterator.md) for exceptions indicating errors with iterators - [`type_error`](type_error.md) for exceptions indicating executing a member function with a wrong type - [`out_of_range`](out_of_range.md) for exceptions indicating access out of the defined range - [`other_error`](other_error.md) for exceptions indicating other library errors ## Member functions - **what** - returns explanatory string ## Member variables - **id** - the id of the exception ## Notes To have nothrow-copy-constructible exceptions, we internally use `std::runtime_error` which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor. ## Examples ??? example The following code shows how arbitrary library exceptions can be caught. ```cpp --8<-- "examples/exception.cpp" ``` Output: ```json --8<-- "examples/exception.output" ``` ## See also [List of exceptions](127.0.0.1:8000/home/exceptions/) ## Version history - Since version 3.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/number_float_t.md
.md
2,931
71
# <small>nlohmann::basic_json::</small>number_float_t ```cpp using number_float_t = NumberFloatType; ``` The type used to store JSON numbers (floating-point). [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows: > The representation of numbers is similar to that used in most programming languages. A number is represented in base > 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may > be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, [`number_integer_t`](number_integer_t.md), [`number_unsigned_t`](number_unsigned_t.md) and `number_float_t` are used. To store floating-point numbers in C++, a type is defined by the template parameter `NumberFloatType` which chooses the type to use. ## Notes #### Default type With the default values for `NumberFloatType` (`double`), the default value for `number_float_t` is `#!cpp double`. #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal `01.2` will be serialized to `1.2`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 8259](https://tools.ietf.org/html/rfc8259) states: > This specification allows implementations to set limits on the range and precision of numbers accepted. Since software > that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good > interoperability can be achieved by implementations that expect no more precision or range than these provide, in the > sense that implementations will approximate JSON numbers within the expected precision. This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` will be stored as NaN internally and be serialized to `null`. #### Storage Floating-point number values are stored directly inside a `basic_json` type. ## Examples ??? example The following code shows that `number_float_t` is by default, a typedef to `#!cpp double`. ```cpp --8<-- "examples/number_float_t.cpp" ``` Output: ```json --8<-- "examples/number_float_t.output" ``` ## Version history - Added in version 1.0.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/input_format_t.md
.md
847
53
# <small>nlohmann::basic_json::</small>input_format_t ```cpp enum class input_format_t { json, cbor, msgpack, ubjson, bson, bjdata }; ``` This enumeration is used in the [`sax_parse`](sax_parse.md) function to choose the input format to parse: json : JSON (JavaScript Object Notation) cbor : CBOR (Concise Binary Object Representation) msgpack : MessagePack ubjson : UBJSON (Universal Binary JSON) bson : BSON (Binary JSON) bjdata : BJData (Binary JData) ## Examples ??? example The example below shows how an `input_format_t` enum value is passed to `sax_parse` to set the input format to CBOR. ```cpp --8<-- "examples/sax_parse__binary.cpp" ``` Output: ```json --8<-- "examples/sax_parse__binary.output" ``` ## Version history - Added in version 3.2.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/to_msgpack.md
.md
1,433
60
# <small>nlohmann::basic_json::</small>to_msgpack ```cpp // (1) static std::vector<std::uint8_t> to_msgpack(const basic_json& j); // (2) static void to_msgpack(const basic_json& j, detail::output_adapter<std::uint8_t> o); static void to_msgpack(const basic_json& j, detail::output_adapter<char> o); ``` Serializes a given JSON value `j` to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. 1. Returns a byte vector containing the MessagePack serialization. 2. Writes the MessagePack serialization to an output adapter. The exact mapping and its limitations is described on a [dedicated page](../../features/binary_formats/messagepack.md). ## Parameters `j` (in) : JSON value to serialize `o` (in) : output adapter to write serialization to ## Return value 1. MessagePack serialization as byte vector 2. (none) ## Exception safety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. ## Complexity Linear in the size of the JSON value `j`. ## Examples ??? example The example shows the serialization of a JSON value to a byte vector in MessagePack format. ```cpp --8<-- "examples/to_msgpack.cpp" ``` Output: ```json --8<-- "examples/to_msgpack.output" ``` ## Version history - Added in version 2.0.9.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/api/basic_json/is_binary.md
.md
664
40
# <small>nlohmann::basic_json::</small>is_binary ```cpp constexpr bool is_binary() const noexcept; ``` This function returns `#!cpp true` if and only if the JSON value is binary array. ## Return value `#!cpp true` if type is binary, `#!cpp false` otherwise. ## Exception safety No-throw guarantee: this member function never throws exceptions. ## Complexity Constant. ## Examples ??? example The following code exemplifies `is_binary()` for all JSON types. ```cpp --8<-- "examples/is_binary.cpp" ``` Output: ```json --8<-- "examples/is_binary.output" ``` ## Version history - Added in version 3.8.0.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/macros.md
.md
8,236
154
# Supported Macros Some aspects of the library can be configured by defining preprocessor macros before including the `json.hpp` header. See also the [API documentation for macros](../api/macros/index.md) for examples and more information. ## `JSON_ASSERT(x)` This macro controls which code is executed for [runtime assertions](assertions.md) of the library. See [full documentation of `JSON_ASSERT(x)`](../api/macros/json_assert.md). ## `JSON_CATCH_USER(exception)` This macro overrides [`#!cpp catch`](https://en.cppreference.com/w/cpp/language/try_catch) calls inside the library. See [full documentation of `JSON_CATCH_USER(exception)`](../api/macros/json_throw_user.md). ## `JSON_DIAGNOSTICS` This macro enables extended diagnostics for exception messages. Possible values are `1` to enable or `0` to disable (default). When enabled, exception messages contain a [JSON Pointer](json_pointer.md) to the JSON value that triggered the exception, see [Extended diagnostic messages](../home/exceptions.md#extended-diagnostic-messages) for an example. Note that enabling this macro increases the size of every JSON value by one pointer and adds some runtime overhead. The diagnostics messages can also be controlled with the CMake option `JSON_Diagnostics` (`OFF` by default) which sets `JSON_DIAGNOSTICS` accordingly. See [full documentation of `JSON_DIAGNOSTICS`](../api/macros/json_diagnostics.md). ## `JSON_HAS_CPP_11`, `JSON_HAS_CPP_14`, `JSON_HAS_CPP_17`, `JSON_HAS_CPP_20` The library targets C++11, but also supports some features introduced in later C++ versions (e.g., `std::string_view` support for C++17). For these new features, the library implements some preprocessor checks to determine the C++ standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be detected incorrectly. See [full documentation of `JSON_HAS_CPP_11`, `JSON_HAS_CPP_14`, `JSON_HAS_CPP_17`, and `JSON_HAS_CPP_20`](../api/macros/json_has_cpp_11.md). ## `JSON_HAS_FILESYSTEM`, `JSON_HAS_EXPERIMENTAL_FILESYSTEM` When compiling with C++17, the library provides conversions from and to `std::filesystem::path`. As compiler support for filesystem is limited, the library tries to detect whether `<filesystem>`/`std::filesystem` (`JSON_HAS_FILESYSTEM`) or `<experimental/filesystem>`/`std::experimental::filesystem` (`JSON_HAS_EXPERIMENTAL_FILESYSTEM`) should be used. To override the built-in check, define `JSON_HAS_FILESYSTEM` or `JSON_HAS_EXPERIMENTAL_FILESYSTEM` to `1`. See [full documentation of `JSON_HAS_FILESYSTEM` and `JSON_HAS_EXPERIMENTAL_FILESYSTEM`](../api/macros/json_has_filesystem.md). ## `JSON_NOEXCEPTION` Exceptions can be switched off by defining the symbol `JSON_NOEXCEPTION`. See [full documentation of `JSON_NOEXCEPTION`](../api/macros/json_noexception.md). ## `JSON_DISABLE_ENUM_SERIALIZATION` When defined, default parse and serialize functions for enums are excluded and have to be provided by the user, for example, using [`NLOHMANN_JSON_SERIALIZE_ENUM`](../api/macros/nlohmann_json_serialize_enum.md). See [full documentation of `JSON_DISABLE_ENUM_SERIALIZATION`](../api/macros/json_disable_enum_serialization.md). ## `JSON_NO_IO` When defined, headers `<cstdio>`, `<ios>`, `<iosfwd>`, `<istream>`, and `<ostream>` are not included and parse functions relying on these headers are excluded. This is relevant for environment where these I/O functions are disallowed for security reasons (e.g., Intel Software Guard Extensions (SGX)). See [full documentation of `JSON_NO_IO`](../api/macros/json_no_io.md). ## `JSON_SKIP_LIBRARY_VERSION_CHECK` When defined, the library will not create a compiler warning when a different version of the library was already included. See [full documentation of `JSON_SKIP_LIBRARY_VERSION_CHECK`](../api/macros/json_skip_library_version_check.md). ## `JSON_SKIP_UNSUPPORTED_COMPILER_CHECK` When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used. See [full documentation of `JSON_SKIP_UNSUPPORTED_COMPILER_CHECK`](../api/macros/json_skip_unsupported_compiler_check.md). ## `JSON_THROW_USER(exception)` This macro overrides `#!cpp throw` calls inside the library. The argument is the exception to be thrown. See [full documentation of `JSON_THROW_USER(exception)`](../api/macros/json_throw_user.md). ## `JSON_TRY_USER` This macro overrides `#!cpp try` calls inside the library. See [full documentation of `JSON_TRY_USER`](../api/macros/json_throw_user.md). ## `JSON_USE_IMPLICIT_CONVERSIONS` When defined to `0`, implicit conversions are switched off. By default, implicit conversions are switched on. See [full documentation of `JSON_USE_IMPLICIT_CONVERSIONS`](../api/macros/json_use_implicit_conversions.md). ## `NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)` This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object. The macro is to be defined inside the class/struct to create code for. Unlike [`NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE`](#nlohmann_define_type_non_intrusivetype-member), it can access private members. The first parameter is the name of the class/struct, and all remaining parameters name the members. See [full documentation of `NLOHMANN_DEFINE_TYPE_INTRUSIVE`](../api/macros/nlohmann_define_type_intrusive.md). ## `NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...)` This macro is similar to `NLOHMANN_DEFINE_TYPE_INTRUSIVE`. It will not throw an exception in `from_json()` due to a missing value in the JSON object, but can throw due to a mismatched type. The `from_json()` function default constructs an object and uses its values as the defaults when calling the [`value`](../api/basic_json/value.md) function. See [full documentation of `NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT`](../api/macros/nlohmann_define_type_intrusive.md). ## `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)` This macro can be used to simplify the serialization/deserialization of types if (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object. The macro is to be defined inside the namespace of the class/struct to create code for. Private members cannot be accessed. Use [`NLOHMANN_DEFINE_TYPE_INTRUSIVE`](#nlohmann_define_type_intrusivetype-member) in these scenarios. The first parameter is the name of the class/struct, and all remaining parameters name the members. See [full documentation of `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE`](../api/macros/nlohmann_define_type_non_intrusive.md). ## `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...)` This macro is similar to `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE`. It will not throw an exception in `from_json()` due to a missing value in the JSON object, but can throw due to a mismatched type. The `from_json()` function default constructs an object and uses its values as the defaults when calling the [`value`](../api/basic_json/value.md) function. See [full documentation of `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT`](../api/macros/nlohmann_define_type_non_intrusive.md). ## `NLOHMANN_JSON_SERIALIZE_ENUM(type, ...)` This macro simplifies the serialization/deserialization of enum types. See [Specializing enum conversion](enum_conversion.md) for more information. See [full documentation of `NLOHMANN_JSON_SERIALIZE_ENUM`](../api/macros/nlohmann_json_serialize_enum.md). ## `NLOHMANN_JSON_VERSION_MAJOR`, `NLOHMANN_JSON_VERSION_MINOR`, `NLOHMANN_JSON_VERSION_PATCH` These macros are defined by the library and contain the version numbers according to [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html). See [full documentation of `NLOHMANN_JSON_VERSION_MAJOR`, `NLOHMANN_JSON_VERSION_MINOR`, and `NLOHMANN_JSON_VERSION_PATCH`](../api/macros/nlohmann_json_version_major.md).
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/object_order.md
.md
2,678
110
# Object Order The [JSON standard](https://tools.ietf.org/html/rfc8259.html) defines objects as "an unordered collection of zero or more name/value pairs". As such, an implementation does not need to preserve any specific order of object keys. ## Default behavior: sort keys The default type `nlohmann::json` uses a `std::map` to store JSON objects, and thus stores object keys **sorted alphabetically**. ??? example ```cpp #include <iostream> #include "json.hpp" using json = nlohmann::json; int main() { json j; j["one"] = 1; j["two"] = 2; j["three"] = 3; std::cout << j.dump(2) << '\n'; } ``` Output: ```json { "one": 1, "three": 3, "two": 2 } ``` ## Alternative behavior: preserve insertion order If you do want to preserve the **insertion order**, you can try the type [`nlohmann::ordered_json`](https://github.com/nlohmann/json/issues/2179). ??? example ```cpp --8<-- "examples/ordered_json.cpp" ``` Output: ```json --8<-- "examples/ordered_json.output" ``` Alternatively, you can use a more sophisticated ordered map like [`tsl::ordered_map`](https://github.com/Tessil/ordered-map) ([integration](https://github.com/nlohmann/json/issues/546#issuecomment-304447518)) or [`nlohmann::fifo_map`](https://github.com/nlohmann/fifo_map) ([integration](https://github.com/nlohmann/json/issues/485#issuecomment-333652309)). ### Notes on parsing Note that you also need to call the right [`parse`](../api/basic_json/parse.md) function when reading from a file. Assume file `input.json` contains the JSON object above: ```json { "one": 1, "two": 2, "three": 3 } ``` !!! success "Right way" The following code correctly calls the `parse` function from `nlohmann::ordered_json`: ```cpp std::ifstream i("input.json"); auto j = nlohmann::ordered_json::parse(i); std::cout << j.dump(2) << std::endl; ``` The output will be: ```json { "one": 1, "two": 2, "three": 3 } ``` ??? failure "Wrong way" The following code incorrectly calls the `parse` function from `nlohmann::json` which does not preserve the insertion order, but sorts object keys. Assigning the result to `nlohmann::ordered_json` compiles, but does not restore the order from the input file. ```cpp std::ifstream i("input.json"); nlohmann::ordered_json j = nlohmann::json::parse(i); std::cout << j.dump(2) << std::endl; ``` The output will be: ```json { "one": 1, "three": 3 "two": 2, } ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/enum_conversion.md
.md
2,341
62
# Specializing enum conversion By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended. It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below: ```cpp // example enum type declaration enum TaskState { TS_STOPPED, TS_RUNNING, TS_COMPLETED, TS_INVALID=-1, }; // map TaskState values to JSON as strings NLOHMANN_JSON_SERIALIZE_ENUM( TaskState, { {TS_INVALID, nullptr}, {TS_STOPPED, "stopped"}, {TS_RUNNING, "running"}, {TS_COMPLETED, "completed"}, }) ``` The [`NLOHMANN_JSON_SERIALIZE_ENUM()` macro](../api/macros/nlohmann_json_serialize_enum.md) declares a set of `to_json()` / `from_json()` functions for type `TaskState` while avoiding repetition and boilerplate serialization code. ## Usage ```cpp // enum to JSON as string json j = TS_STOPPED; assert(j == "stopped"); // json string to enum json j3 = "running"; assert(j3.template get<TaskState>() == TS_RUNNING); // undefined json value to enum (where the first map entry above is the default) json jPi = 3.14; assert(jPi.template get<TaskState>() == TS_INVALID ); ``` ## Notes Just as in [Arbitrary Type Conversions](arbitrary_types.md) above, - [`NLOHMANN_JSON_SERIALIZE_ENUM()`](../api/macros/nlohmann_json_serialize_enum.md) MUST be declared in your enum type's namespace (which can be the global namespace), or the library will not be able to locate it, and it will default to integer serialization. - It MUST be available (e.g., proper headers must be included) everywhere you use the conversions. Other Important points: - When using `template get<ENUM_TYPE>()`, undefined JSON values will default to the first pair specified in your map. Select this default pair carefully. - If an enum or JSON value is specified more than once in your map, the first matching occurrence from the top of the map will be returned when converting to or from JSON. - To disable the default serialization of enumerators as integers and force a compiler error instead, see [`JSON_DISABLE_ENUM_SERIALIZATION`](../api/macros/json_disable_enum_serialization.md).
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/json_patch.md
.md
1,033
48
# JSON Patch and Diff ## Patches JSON Patch ([RFC 6902](https://tools.ietf.org/html/rfc6902)) defines a JSON document structure for expressing a sequence of operations to apply to a JSON document. With the `patch` function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. ??? example The following code shows how a JSON patch is applied to a value. ```cpp --8<-- "examples/patch.cpp" ``` Output: ```json --8<-- "examples/patch.output" ``` ## Diff The library can also calculate a JSON patch (i.e., a **diff**) given two JSON values. !!! success "Invariant" For two JSON values *source* and *target*, the following code yields always true: ```cüü source.patch(diff(source, target)) == target; ``` ??? example The following code shows how a JSON patch is created as a diff for two JSON values. ```cpp --8<-- "examples/diff.cpp" ``` Output: ```json --8<-- "examples/diff.output" ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/json_pointer.md
.md
4,288
127
# JSON Pointer ## Introduction The library supports **JSON Pointer** ([RFC 6901](https://tools.ietf.org/html/rfc6901)) as alternative means to address structured values. A JSON Pointer is a string that identifies a specific value within a JSON document. Consider the following JSON document ```json { "array": ["A", "B", "C"], "nested": { "one": 1, "two": 2, "three": [true, false] } } ``` Then every value inside the JSON document can be identified as follows: | JSON Pointer | JSON value | |-------------------|----------------------------------------------------------------------------------| | `` | `#!json {"array":["A","B","C"],"nested":{"one":1,"two":2,"three":[true,false]}}` | | `/array` | `#!json ["A","B","C"]` | | `/array/0` | `#!json A` | | `/array/1` | `#!json B` | | `/array/2` | `#!json C` | | `/nested` | `#!json {"one":1,"two":2,"three":[true,false]}` | | `/nested/one` | `#!json 1` | | `/nested/two` | `#!json 2` | | `/nested/three` | `#!json [true,false]` | | `/nested/three/0` | `#!json true` | | `/nested/three/1` | `#!json false` | Note `/` does not identify the root (i.e., the whole document), but an object entry with empty key `""`. See [RFC 6901](https://tools.ietf.org/html/rfc6901) for more information. ## JSON Pointer creation JSON Pointers can be created from a string: ```cpp json::json_pointer p = "/nested/one"; ``` Furthermore, a user-defined string literal can be used to achieve the same result: ```cpp auto p = "/nested/one"_json_pointer; ``` The escaping rules of [RFC 6901](https://tools.ietf.org/html/rfc6901) are implemented. See the [constructor documentation](../api/json_pointer/json_pointer.md) for more information. ## Value access JSON Pointers can be used in the [`at`](../api/basic_json/at.md), [`operator[]`](../api/basic_json/operator%5B%5D.md), and [`value`](../api/basic_json/value.md) functions just like object keys or array indices. ```cpp // the JSON value from above auto j = json::parse(R"({ "array": ["A", "B", "C"], "nested": { "one": 1, "two": 2, "three": [true, false] } })"); // access values auto val = j["/"_json_pointer]; // {"array":["A","B","C"],...} auto val1 = j["/nested/one"_json_pointer]; // 1 auto val2 = j.at[json::json_pointer("/nested/three/1")]; // false auto val3 = j.value[json::json_pointer("/nested/four", 0)]; // 0 ``` ## Flatten / unflatten The library implements a function [`flatten`](../api/basic_json/flatten.md) to convert any JSON document into a JSON object where each key is a JSON Pointer and each value is a primitive JSON value (i.e., a string, boolean, number, or null). ```cpp // the JSON value from above auto j = json::parse(R"({ "array": ["A", "B", "C"], "nested": { "one": 1, "two": 2, "three": [true, false] } })"); // create flattened value auto j_flat = j.flatten(); ``` The resulting value `j_flat` is: ```json { "/array/0": "A", "/array/1": "B", "/array/2": "C", "/nested/one": 1, "/nested/two": 2, "/nested/three/0": true, "/nested/three/1": false } ``` The reverse function, [`unflatten`](../api/basic_json/unflatten.md) recreates the original value. ```cpp auto j_original = j_flat.unflatten(); ``` ## See also - Class [`json_pointer`](../api/json_pointer/index.md) - Function [`flatten`](../api/basic_json/flatten.md) - Function [`unflatten`](../api/basic_json/unflatten.md) - [JSON Patch](json_patch.md)
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/arbitrary_types.md
.md
11,424
275
# Arbitrary Type Conversions Every type can be serialized in JSON, not just STL containers and scalar types. Usually, you would do something along those lines: ```cpp namespace ns { // a simple struct to model a person struct person { std::string name; std::string address; int age; }; } // namespace ns ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60}; // convert to JSON: copy each value into the JSON object json j; j["name"] = p.name; j["address"] = p.address; j["age"] = p.age; // ... // convert from JSON: copy each value from the JSON object ns::person p { j["name"].template get<std::string>(), j["address"].template get<std::string>(), j["age"].template get<int>() }; ``` It works, but that's quite a lot of boilerplate... Fortunately, there's a better way: ```cpp // create a person ns::person p {"Ned Flanders", "744 Evergreen Terrace", 60}; // conversion: person -> json json j = p; std::cout << j << std::endl; // {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"} // conversion: json -> person auto p2 = j.template get<ns::person>(); // that's it assert(p == p2); ``` ## Basic usage To make this work with one of your types, you only need to provide two functions: ```cpp using json = nlohmann::json; namespace ns { void to_json(json& j, const person& p) { j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age} }; } void from_json(const json& j, person& p) { j.at("name").get_to(p.name); j.at("address").get_to(p.address); j.at("age").get_to(p.age); } } // namespace ns ``` That's all! When calling the `json` constructor with your type, your custom `to_json` method will be automatically called. Likewise, when calling `template get<your_type>()` or `get_to(your_type&)`, the `from_json` method will be called. Some important things: * Those methods **MUST** be in your type's namespace (which can be the global namespace), or the library will not be able to locate them (in this example, they are in namespace `ns`, where `person` is defined). * Those methods **MUST** be available (e.g., proper headers must be included) everywhere you use these conversions. Look at [issue 1108](https://github.com/nlohmann/json/issues/1108) for errors that may occur otherwise. * When using `template get<your_type>()`, `your_type` **MUST** be [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). (There is a way to bypass this requirement described later.) * In function `from_json`, use function [`at()`](../api/basic_json/at.md) to access the object values rather than `operator[]`. In case a key does not exist, `at` throws an exception that you can handle, whereas `operator[]` exhibits undefined behavior. * You do not need to add serializers or deserializers for STL types like `std::vector`: the library already implements these. ## Simplify your life with macros If you just want to serialize/deserialize some structs, the `to_json`/`from_json` functions can be a lot of boilerplate. There are four macros to make your life easier as long as you (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object: - [`NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(name, member1, member2, ...)`](../api/macros/nlohmann_define_type_non_intrusive.md) is to be defined inside the namespace of the class/struct to create code for. It will throw an exception in `from_json()` due to a missing value in the JSON object. - [`NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...)`](../api/macros/nlohmann_define_type_non_intrusive.md) is to be defined inside the namespace of the class/struct to create code for. It will not throw an exception in `from_json()` due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type. - [`NLOHMANN_DEFINE_TYPE_INTRUSIVE(name, member1, member2, ...)`](../api/macros/nlohmann_define_type_intrusive.md) is to be defined inside the class/struct to create code for. This macro can also access private members. It will throw an exception in `from_json()` due to a missing value in the JSON object. - [`NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(name, member1, member2, ...)`](../api/macros/nlohmann_define_type_intrusive.md) is to be defined inside the class/struct to create code for. This macro can also access private members. It will not throw an exception in `from_json()` due to a missing value in the JSON object, but fills in values from object which is default-constructed by the type. In all macros, the first parameter is the name of the class/struct, and all remaining parameters name the members. You can read more docs about them starting from [here](macros.md#nlohmann_define_type_intrusivetype-member). !!! info "Implementation limits" - The current macro implementations are limited to at most 64 member variables. If you want to serialize/deserialize types with more than 64 member variables, you need to define the `to_json`/`from_json` functions manually. - The macros only work for the [`nlohmann::json`](../api/json.md) type; other specializations such as [`nlohmann::ordered_json`](../api/ordered_json.md) are currently unsupported. ??? example The `to_json`/`from_json` functions for the `person` struct above can be created with: ```cpp namespace ns { NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age) } ``` Here is an example with private members, where `NLOHMANN_DEFINE_TYPE_INTRUSIVE` is needed: ```cpp namespace ns { class address { private: std::string street; int housenumber; int postcode; public: NLOHMANN_DEFINE_TYPE_INTRUSIVE(address, street, housenumber, postcode) }; } ``` ## How do I convert third-party types? This requires a bit more advanced technique. But first, let's see how this conversion mechanism works: The library uses **JSON Serializers** to convert types to json. The default serializer for `nlohmann::json` is `nlohmann::adl_serializer` (ADL means [Argument-Dependent Lookup](https://en.cppreference.com/w/cpp/language/adl)). It is implemented like this (simplified): ```cpp template <typename T> struct adl_serializer { static void to_json(json& j, const T& value) { // calls the "to_json" method in T's namespace } static void from_json(const json& j, T& value) { // same thing, but with the "from_json" method } }; ``` This serializer works fine when you have control over the type's namespace. However, what about `boost::optional` or `std::filesystem::path` (C++17)? Hijacking the `boost` namespace is pretty bad, and it's illegal to add something other than template specializations to `std`... To solve this, you need to add a specialization of `adl_serializer` to the `nlohmann` namespace, here's an example: ```cpp // partial specialization (full specialization works too) NLOHMANN_JSON_NAMESPACE_BEGIN template <typename T> struct adl_serializer<boost::optional<T>> { static void to_json(json& j, const boost::optional<T>& opt) { if (opt == boost::none) { j = nullptr; } else { j = *opt; // this will call adl_serializer<T>::to_json which will // find the free function to_json in T's namespace! } } static void from_json(const json& j, boost::optional<T>& opt) { if (j.is_null()) { opt = boost::none; } else { opt = j.template get<T>(); // same as above, but with // adl_serializer<T>::from_json } } }; NLOHMANN_JSON_NAMESPACE_END ``` !!! note "ABI compatibility" Use [`NLOHMANN_JSON_NAMESPACE_BEGIN`](../api/macros/nlohmann_json_namespace_begin.md) and `NLOHMANN_JSON_NAMESPACE_END` instead of `#!cpp namespace nlohmann { }` in code which may be linked with different versions of this library. ## How can I use `get()` for non-default constructible/non-copyable types? There is a way, if your type is [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible). You will need to specialize the `adl_serializer` as well, but with a special `from_json` overload: ```cpp struct move_only_type { move_only_type() = delete; move_only_type(int ii): i(ii) {} move_only_type(const move_only_type&) = delete; move_only_type(move_only_type&&) = default; int i; }; namespace nlohmann { template <> struct adl_serializer<move_only_type> { // note: the return type is no longer 'void', and the method only takes // one argument static move_only_type from_json(const json& j) { return {j.template get<int>()}; } // Here's the catch! You must provide a to_json method! Otherwise, you // will not be able to convert move_only_type to json, since you fully // specialized adl_serializer on that type static void to_json(json& j, move_only_type t) { j = t.i; } }; } ``` ## Can I write my own serializer? (Advanced use) Yes. You might want to take a look at [`unit-udt.cpp`](https://github.com/nlohmann/json/blob/develop/tests/src/unit-udt.cpp) in the test suite, to see a few examples. If you write your own serializer, you'll need to do a few things: - use a different `basic_json` alias than `nlohmann::json` (the last template parameter of `basic_json` is the `JSONSerializer`) - use your `basic_json` alias (or a template parameter) in all your `to_json`/`from_json` methods - use `nlohmann::to_json` and `nlohmann::from_json` when you need ADL Here is an example, without simplifications, that only accepts types with a size <= 32, and uses ADL. ```cpp // You should use void as a second template argument // if you don't need compile-time checks on T template<typename T, typename SFINAE = typename std::enable_if<sizeof(T) <= 32>::type> struct less_than_32_serializer { template <typename BasicJsonType> static void to_json(BasicJsonType& j, T value) { // we want to use ADL, and call the correct to_json overload using nlohmann::to_json; // this method is called by adl_serializer, // this is where the magic happens to_json(j, value); } template <typename BasicJsonType> static void from_json(const BasicJsonType& j, T& value) { // same thing here using nlohmann::from_json; from_json(j, value); } }; ``` Be **very** careful when reimplementing your serializer, you can stack overflow if you don't pay attention: ```cpp template <typename T, void> struct bad_serializer { template <typename BasicJsonType> static void to_json(BasicJsonType& j, const T& value) { // this calls BasicJsonType::json_serializer<T>::to_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! j = value; } template <typename BasicJsonType> static void to_json(const BasicJsonType& j, T& value) { // this calls BasicJsonType::json_serializer<T>::from_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! value = j.template template get<T>(); // oops! } }; ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/namespace.md
.md
4,265
94
# `nlohmann` Namespace The 3.11.0 release introduced an [inline namespace](https://en.cppreference.com/w/cpp/language/namespace#Inline_namespaces) to allow different parts of a codebase to safely use different versions of the JSON library as long as they never exchange instances of library types. ## Structure The complete default namespace name is derived as follows: - The root namespace is always `nlohmann`. - The inline namespace starts with `json_abi` and is followed by serveral optional ABI tags according to the value of these ABI-affecting macros, in order: - [`JSON_DIAGNOSTICS`](../api/macros/json_diagnostics.md) defined non-zero appends `_diag`. - [`JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON`](../api/macros/json_use_legacy_discarded_value_comparison.md) defined non-zero appends `_ldvcmp`. - The inline namespace ends with the suffix `_v` followed by the 3 components of the version number separated by underscores. To omit the version component, see [Disabling the version component](#disabling-the-version-component) below. For example, the namespace name for version 3.11.2 with `JSON_DIAGNOSTICS` defined to `1` is: ```cpp nlohmann::json_abi_diag_v3_11_2 ``` ## Purpose Several incompatibilities have been observed. Amongst the most common ones is linking code compiled with different definitions of [`JSON_DIAGNOSTICS`](../api/macros/json_diagnostics.md). This is illustrated in the diagram below. ```plantuml [**nlohmann_json (v3.10.5)**\nJSON_DIAGNOSTICS=0] as [json] [**nlohmann_json (v3.10.5)**\nJSON_DIAGNOSTICS=1] as [json_diag] [**some_library**] as [library] [**application**] as [app] [library] ..|> [json] [app] ..|> [json_diag] [app] ..|>[library] ``` In releases prior to 3.11.0, mixing any version of the JSON library with different `JSON_DIAGNOSTICS` settings would result in a crashing application. If `some_library` never passes instances of JSON library types to the application, this scenario became safe in version 3.11.0 and above due to the inline namespace yielding distinct symbol names. ## Limitations Neither the compiler nor the linker will issue as much as a warning when translation units – intended to be linked together and that include different versions and/or configurations of the JSON library – exchange and use library types. There is an exception when forward declarations are used (i.e., when including `json_fwd.hpp`) in which case the linker may complain about undefined references. ## Disabling the version component Different versions are not necessarily ABI-incompatible, but the project does not actively track changes in the ABI and recommends that all parts of a codebase exchanging library types be built with the same version. Users can, **at their own risk**, disable the version component of the linline namespace, allowing different versions – but not configurations – to be used in cases where the linker would otherwise output undefined reference errors. To do so, define [`NLOHMANN_JSON_NAMESPACE_NO_VERSION`](../api/macros/nlohmann_json_namespace_no_version.md) to `1`. This applies to version 3.11.2 and above only, versions 3.11.0 and 3.11.1 can apply the technique described in the next section to emulate the effect of the `NLOHMANN_JSON_NAMESPACE_NO_VERSION` macro. !!! danger "Use at your own risk" Disabling the namespace version component and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned! ## Disabling the inline namespace completely When interoperability with code using a pre-3.11.0 version of the library is required, users can, **at their own risk** restore the old namespace layout by redefining [`NLOHMANN_JSON_NAMESPACE_BEGIN, NLOHMANN_JSON_NAMESPACE_END`](../api/macros/nlohmann_json_namespace_begin.md) as follows: ```cpp #define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann { #define NLOHMANN_JSON_NAMESPACE_END } ``` !!! danger "Use at your own risk" Overriding the namespace and mixing ABI-incompatible versions will result in crashes or incorrect behavior. You have been warned! ## Version history - Introduced inline namespace (`json_v3_11_0[_abi-tag]*`) in version 3.11.0. - Changed structure of inline namespace in version 3.11.2.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/iterators.md
.md
4,109
156
# Iterators ## Overview A `basic_json` value is a container and allows access via iterators. Depending on the value type, `basic_json` stores zero or more values. As for other containers, `begin()` returns an iterator to the first value and `end()` returns an iterator to the value following the last value. The latter iterator is a placeholder and cannot be dereferenced. In case of null values, empty arrays, or empty objects, `begin()` will return `end()`. ![Illustration from cppreference.com](../images/range-begin-end.svg) ### Iteration order for objects When iterating over objects, values are ordered with respect to the `object_comparator_t` type which defaults to `std::less`. See the [types documentation](types/index.md#key-order) for more information. ??? example ```cpp // create JSON object {"one": 1, "two": 2, "three": 3} json j; j["one"] = 1; j["two"] = 2; j["three"] = 3; for (auto it = j.begin(); it != j.end(); ++it) { std::cout << *it << std::endl; } ``` Output: ```json 1 3 2 ``` The reason for the order is the lexicographic ordering of the object keys "one", "three", "two". ### Access object key during iteration The JSON iterators have two member functions, `key()` and `value()` to access the object key and stored value, respectively. When calling `key()` on a non-object iterator, an [invalid_iterator.207](../home/exceptions.md#jsonexceptioninvalid_iterator207) exception is thrown. ??? example ```cpp // create JSON object {"one": 1, "two": 2, "three": 3} json j; j["one"] = 1; j["two"] = 2; j["three"] = 3; for (auto it = j.begin(); it != j.end(); ++it) { std::cout << it.key() << " : " << it.value() << std::endl; } ``` Output: ```json one : 1 three : 3 two : 2 ``` ### Range-based for loops C++11 allows using range-based for loops to iterate over a container. ```cpp for (auto it : j_object) { // "it" is of type json::reference and has no key() member std::cout << "value: " << it << '\n'; } ``` For this reason, the `items()` function allows accessing `iterator::key()` and `iterator::value()` during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator. ```cpp for (auto& el : j_object.items()) { std::cout << "key: " << el.key() << ", value:" << el.value() << '\n'; } ``` The items() function also allows using structured bindings (C++17): ```cpp for (auto& [key, val] : j_object.items()) { std::cout << "key: " << key << ", value:" << val << '\n'; } ``` !!! note When iterating over an array, `key()` will return the index of the element as string. For primitive types (e.g., numbers), `key()` returns an empty string. !!! warning Using `items()` on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See <https://github.com/nlohmann/json/issues/2040> for more information. ### Reverse iteration order `rbegin()` and `rend()` return iterators in the reverse sequence. ![Illustration from cppreference.com](../images/range-rbegin-rend.svg) ??? example ```cpp json j = {1, 2, 3, 4}; for (auto it = j.rbegin(); it != j.rend(); ++it) { std::cout << *it << std::endl; } ``` Output: ```json 4 3 2 1 ``` ### Iterating strings and binary values Note that "value" means a JSON value in this setting, not values stored in the underlying containers. That is, `*begin()` returns the complete string or binary array and is also safe the underlying string or binary array is empty. ??? example ```cpp json j = "Hello, world"; for (auto it = j.begin(); it != j.end(); ++it) { std::cout << *it << std::endl; } ``` Output: ```json "Hello, world" ``` ## Iterator invalidation | Operations | invalidated iterators | |------------|-----------------------| | `clear` | all |
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/comments.md
.md
2,955
84
# Comments This library does not support comments *by default*. It does so for three reasons: 1. Comments are not part of the [JSON specification](https://tools.ietf.org/html/rfc8259). You may argue that `//` or `/* */` are allowed in JavaScript, but JSON is not JavaScript. 2. This was not an oversight: Douglas Crockford [wrote on this](https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr) in May 2012: > I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't. > Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser. 3. It is dangerous for interoperability if some libraries would add comment support while others don't. Please check [The Harmful Consequences of the Robustness Principle](https://tools.ietf.org/html/draft-iab-protocol-maintenance-01) on this. However, you can pass set parameter `ignore_comments` to `#!c true` in the parse function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace. !!! example Consider the following JSON with comments. ```json { // update in 2006: removed Pluto "planets": ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Uranus", "Neptune" /*, "Pluto" */] } ``` When calling `parse` without additional argument, a parse error exception is thrown. If `ignore_comments` is set to `#! true`, the comments are ignored during parsing: ```cpp #include <iostream> #include "json.hpp" using json = nlohmann::json; int main() { std::string s = R"( { // update in 2006: removed Pluto "planets": ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Uranus", "Neptune" /*, "Pluto" */] } )"; try { json j = json::parse(s); } catch (json::exception &e) { std::cout << e.what() << std::endl; } json j = json::parse(s, /* callback */ nullptr, /* allow exceptions */ true, /* ignore_comments */ true); std::cout << j.dump(2) << '\n'; } ``` Output: ``` [json.exception.parse_error.101] parse error at line 3, column 9: syntax error while parsing object key - invalid literal; last read: '<U+000A> {<U+000A> /'; expected string literal ``` ```json { "planets": [ "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Uranus", "Neptune" ] } ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/merge_patch.md
.md
760
21
# JSON Merge Patch The library supports JSON Merge Patch ([RFC 7386](https://tools.ietf.org/html/rfc7386)) as a patch format. The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value. Instead of using [JSON Pointer](json_pointer.md) to specify values to be manipulated, it describes the changes using a syntax that closely mimics the document being modified. ??? example The following code shows how a JSON Merge Patch is applied to a JSON document. ```cpp --8<-- "examples/merge_patch.cpp" ``` Output: ```json --8<-- "examples/merge_patch.output" ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/assertions.md
.md
3,766
132
# Runtime Assertions The code contains numerous debug assertions to ensure class invariants are valid or to detect undefined behavior. Whereas the former class invariants are nothing to be concerned of, the latter checks for undefined behavior are to detect bugs in client code. ## Switch off runtime assertions Runtime assertions can be switched off by defining the preprocessor macro `NDEBUG` (see the [documentation of assert](https://en.cppreference.com/w/cpp/error/assert)) which is the default for release builds. ## Change assertion behavior The behavior of runtime assertions can be changes by defining macro [`JSON_ASSERT(x)`](../api/macros/json_assert.md) before including the `json.hpp` header. ## Function with runtime assertions ### Unchecked object access to a const value Function [`operator[]`](../api/basic_json/operator%5B%5D.md) implements unchecked access for objects. Whereas a missing key is added in case of non-const objects, accessing a const object with a missing key is undefined behavior (think of a dereferenced null pointer) and yields a runtime assertion. If you are not sure whether an element in an object exists, use checked access with the [`at` function](../api/basic_json/at.md) or call the [`contains` function](../api/basic_json/contains.md) before. See also the documentation on [element access](element_access/index.md). ??? example "Example 1: Missing object key" The following code will trigger an assertion at runtime: ```cpp #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { const json j = {{"key", "value"}}; auto v = j["missing"]; } ``` Output: ``` Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144. ``` ### Constructing from an uninitialized iterator range Constructing a JSON value from an iterator range (see [constructor](../api/basic_json/basic_json.md)) with an uninitialized iterator is undefined behavior and yields a runtime assertion. ??? example "Example 2: Uninitialized iterator range" The following code will trigger an assertion at runtime: ```cpp #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { json::iterator it1, it2; json j(it1, it2); } ``` Output: ``` Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368. ``` ### Operations on uninitialized iterators Any operation on uninitialized iterators (i.e., iterators that are not associated with any JSON value) is undefined behavior and yields a runtime assertion. ??? example "Example 3: Uninitialized iterator" The following code will trigger an assertion at runtime: ```cpp #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { json::iterator it; ++it; } ``` Output: ``` Assertion failed: (m_object != nullptr), function operator++, file iter_impl.hpp, line 368. ``` ### Reading from a null `FILE` pointer Reading from a null `#!cpp FILE` pointer is undefined behavior and yields a runtime assertion. This can happen when calling `#!cpp std::fopen` on a nonexistent file. ??? example "Example 4: Uninitialized iterator" The following code will trigger an assertion at runtime: ```cpp #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { std::FILE* f = std::fopen("nonexistent_file.json", "r"); json j = json::parse(f); } ``` Output: ``` Assertion failed: (m_file != nullptr), function file_input_adapter, file input_adapters.hpp, line 55. ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/binary_values.md
.md
11,778
373
# Binary Values The library implements several [binary formats](binary_formats/index.md) that encode JSON in an efficient way. Most of these formats support binary values; that is, values that have semantics define outside the library and only define a sequence of bytes to be stored. JSON itself does not have a binary value. As such, binary values are an extension that this library implements to store values received by a binary format. Binary values are never created by the JSON parser, and are only part of a serialized JSON text if they have been created manually or via a binary format. ## API for binary values ```plantuml class json::binary_t { -- setters -- +void set_subtype(std::uint64_t subtype) +void clear_subtype() -- getters -- +std::uint64_t subtype() const +bool has_subtype() const } "std::vector<uint8_t>" <|-- json::binary_t ``` By default, binary values are stored as `std::vector<std::uint8_t>`. This type can be changed by providing a template parameter to the `basic_json` type. To store binary subtypes, the storage type is extended and exposed as `json::binary_t`: ```cpp auto binary = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE}); auto binary_with_subtype = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE}, 42); ``` There are several convenience functions to check and set the subtype: ```cpp binary.has_subtype(); // returns false binary_with_subtype.has_subtype(); // returns true binary_with_subtype.clear_subtype(); binary_with_subtype.has_subtype(); // returns true binary_with_subtype.set_subtype(42); binary.set_subtype(23); binary.subtype(); // returns 23 ``` As `json::binary_t` is subclassing `std::vector<std::uint8_t>`, all member functions are available: ```cpp binary.size(); // returns 4 binary[1]; // returns 0xFE ``` JSON values can be constructed from `json::binary_t`: ```cpp json j = binary; ``` Binary values are primitive values just like numbers or strings: ```cpp j.is_binary(); // returns true j.is_primitive(); // returns true ``` Given a binary JSON value, the `binary_t` can be accessed by reference as via `get_binary()`: ```cpp j.get_binary().has_subtype(); // returns true j.get_binary().size(); // returns 4 ``` For convenience, binary JSON values can be constructed via `json::binary`: ```cpp auto j2 = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 23); auto j3 = json::binary({0xCA, 0xFE, 0xBA, 0xBE}); j2 == j; // returns true j3.get_binary().has_subtype(); // returns false j3.get_binary().subtype(); // returns std::uint64_t(-1) as j3 has no subtype ``` ## Serialization Binary values are serialized differently according to the formats. ### JSON JSON does not have a binary type, and this library does not introduce a new type as this would break conformance. Instead, binary values are serialized as an object with two keys: `bytes` holds an array of integers, and `subtype` is an integer or `null`. ??? example Code: ```cpp // create a binary value of subtype 42 json j; j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42); // serialize to standard output std::cout << j.dump(2) << std::endl; ``` Output: ```json { "binary": { "bytes": [202, 254, 186, 190], "subtype": 42 } } ``` !!! warning "No roundtrip for binary values" The JSON parser will not parse the objects generated by binary values back to binary values. This is by design to remain standards compliant. Serializing binary values to JSON is only implemented for debugging purposes. ### BJData [BJData](binary_formats/bjdata.md) neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library. ??? example Code: ```cpp // create a binary value of subtype 42 (will be ignored in BJData) json j; j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42); // convert to BJData auto v = json::to_bjdata(j); ``` `v` is a `std::vector<std::uint8t>` with the following 20 elements: ```c 0x7B // '{' 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // "binary" 0x5B // '[' 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U') 0x5D // ']' 0x7D // '}' ``` The following code uses the type and size optimization for UBJSON: ```cpp // convert to UBJSON using the size and type optimization auto v = json::to_bjdata(j, true, true); ``` The resulting vector has 22 elements; the optimization is not effective for examples with few values: ```c 0x7B // '{' 0x23 0x69 0x01 // '#' 'i' type of the array elements: unsigned integers 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // "binary" 0x5B // '[' array 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers 0x23 0x69 0x04 // '#' i 4 number of array elements 0xCA 0xFE 0xBA 0xBE // content ``` Note that subtype (42) is **not** serialized and that UBJSON has **no binary type**, and deserializing `v` would yield the following value: ```json { "binary": [202, 254, 186, 190] } ``` ### BSON [BSON](binary_formats/bson.md) supports binary values and subtypes. If a subtype is given, it is used and added as unsigned 8-bit integer. If no subtype is given, the generic binary subtype 0x00 is used. ??? example Code: ```cpp // create a binary value of subtype 42 json j; j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42); // convert to BSON auto v = json::to_bson(j); ``` `v` is a `std::vector<std::uint8t>` with the following 22 elements: ```c 0x16 0x00 0x00 0x00 // number of bytes in the document 0x05 // binary value 0x62 0x69 0x6E 0x61 0x72 0x79 0x00 // key "binary" + null byte 0x04 0x00 0x00 0x00 // number of bytes 0x2a // subtype 0xCA 0xFE 0xBA 0xBE // content 0x00 // end of the document ``` Note that the serialization preserves the subtype, and deserializing `v` would yield the following value: ```json { "binary": { "bytes": [202, 254, 186, 190], "subtype": 42 } } ``` ### CBOR [CBOR](binary_formats/cbor.md) supports binary values, but no subtypes. Subtypes will be serialized as tags. Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array. ??? example Code: ```cpp // create a binary value of subtype 42 json j; j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42); // convert to CBOR auto v = json::to_cbor(j); ``` `v` is a `std::vector<std::uint8t>` with the following 15 elements: ```c 0xA1 // map(1) 0x66 // text(6) 0x62 0x69 0x6E 0x61 0x72 0x79 // "binary" 0xD8 0x2A // tag(42) 0x44 // bytes(4) 0xCA 0xFE 0xBA 0xBE // content ``` Note that the subtype is serialized as tag. However, parsing tagged values yield a parse error unless `json::cbor_tag_handler_t::ignore` or `json::cbor_tag_handler_t::store` is passed to `json::from_cbor`. ```json { "binary": { "bytes": [202, 254, 186, 190], "subtype": null } } ``` ### MessagePack [MessagePack](binary_formats/messagepack.md) supports binary values and subtypes. If a subtype is given, the ext family is used. The library will choose the smallest representation among fixext1, fixext2, fixext4, fixext8, ext8, ext16, and ext32. The subtype is then added as signed 8-bit integer. If no subtype is given, the bin family (bin8, bin16, bin32) is used. ??? example Code: ```cpp // create a binary value of subtype 42 json j; j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42); // convert to MessagePack auto v = json::to_msgpack(j); ``` `v` is a `std::vector<std::uint8t>` with the following 14 elements: ```c 0x81 // fixmap1 0xA6 // fixstr6 0x62 0x69 0x6E 0x61 0x72 0x79 // "binary" 0xD6 // fixext4 0x2A // subtype 0xCA 0xFE 0xBA 0xBE // content ``` Note that the serialization preserves the subtype, and deserializing `v` would yield the following value: ```json { "binary": { "bytes": [202, 254, 186, 190], "subtype": 42 } } ``` ### UBJSON [UBJSON](binary_formats/ubjson.md) neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library. ??? example Code: ```cpp // create a binary value of subtype 42 (will be ignored in UBJSON) json j; j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42); // convert to UBJSON auto v = json::to_ubjson(j); ``` `v` is a `std::vector<std::uint8t>` with the following 20 elements: ```c 0x7B // '{' 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // "binary" 0x5B // '[' 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U') 0x5D // ']' 0x7D // '}' ``` The following code uses the type and size optimization for UBJSON: ```cpp // convert to UBJSON using the size and type optimization auto v = json::to_ubjson(j, true, true); ``` The resulting vector has 23 elements; the optimization is not effective for examples with few values: ```c 0x7B // '{' 0x24 // '$' type of the object elements 0x5B // '[' array 0x23 0x69 0x01 // '#' i 1 number of object elements 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // "binary" 0x24 0x55 // '$' 'U' type of the array elements: unsigned integers 0x23 0x69 0x04 // '#' i 4 number of array elements 0xCA 0xFE 0xBA 0xBE // content ``` Note that subtype (42) is **not** serialized and that UBJSON has **no binary type**, and deserializing `v` would yield the following value: ```json { "binary": [202, 254, 186, 190] } ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/types/number_handling.md
.md
15,123
329
# Number Handling This document describes how the library is handling numbers. ## Background This section briefly summarizes how the JSON specification describes how numbers should be handled. ### JSON number syntax JSON defines the syntax of numbers as follows: !!! quote "[RFC 8259](https://tools.ietf.org/html/rfc8259#section-6), Section 6" The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. A fraction part is a decimal point followed by one or more digits. An exponent part begins with the letter E in uppercase or lowercase, which may be followed by a plus or minus sign. The E and optional sign are followed by one or more digits. The following railroad diagram from [json.org](https://json.org) visualizes the number syntax: ![Syntax for JSON numbers](../../images/json_syntax_number.png) ### Number interoperability On number interoperability, the following remarks are made: !!! quote "[RFC 8259](https://tools.ietf.org/html/rfc8259#section-6), Section 6" This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754 binary64 (double precision) numbers [IEEE754] is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision. A JSON number such as 1E400 or 3.141592653589793238462643383279 may indicate potential interoperability problems, since it suggests that the software that created it expects receiving software to have greater capabilities for numeric magnitude and precision than is widely available. Note that when such software is used, numbers that are integers and are in the range $[-2^{53}+1, 2^{53}-1]$ are interoperable in the sense that implementations will agree exactly on their numeric values. ## Library implementation This section describes how the above number specification is implemented by this library. ### Number storage In the default [`json`](../../api/json.md) type, numbers are stored as `#!c std::uint64_t`, `#!c std::int64_t`, and `#!c double`, respectively. Thereby, `#!c std::uint64_t` and `#!c std::int64_t` are used only if they can store the number without loss of precision. If this is impossible (e.g., if the number is too large), the number is stored as `#!c double`. !!! info "Notes" - Numbers with a decimal digit or scientific notation are always stored as `#!c double`. - The number types can be changed, see [Template number types](#template-number-types). - As of version 3.9.1, the conversion is realized by [`std::strtoull`](https://en.cppreference.com/w/cpp/string/byte/strtoul), [`std::strtoll`](https://en.cppreference.com/w/cpp/string/byte/strtol), and [`std::strtod`](https://en.cppreference.com/w/cpp/string/byte/strtof), respectively. !!! example "Examples" - Integer `#!c -12345678912345789123456789` is smaller than `#!c INT64_MIN` and will be stored as floating-point number `#!c -1.2345678912345788e+25`. - Integer `#!c 1E3` will be stored as floating-point number `#!c 1000.0`. ### Number limits - Any 64-bit signed or unsigned integer can be stored without loss of precision. - Numbers exceeding the limits of `#!c double` (i.e., numbers that after conversion via [`std::strtod`](https://en.cppreference.com/w/cpp/string/byte/strtof) are not satisfying [`std::isfinite`](https://en.cppreference.com/w/cpp/numeric/math/isfinite) such as `#!c 1E400`) will throw exception [`json.exception.out_of_range.406`](../../home/exceptions.md#jsonexceptionout_of_range406) during parsing. - Floating-point numbers are rounded to the next number representable as `double`. For instance `#!c 3.141592653589793238462643383279` is stored as [`0x400921fb54442d18`](https://float.exposed/0x400921fb54442d18). This is the same behavior as the code `#!c double x = 3.141592653589793238462643383279;`. !!! success "Interoperability" - The library interoperable with respect to the specification, because its supported range $[-2^{63}, 2^{64}-1]$ is larger than the described range $[-2^{53}+1, 2^{53}-1]$. - All integers outside the range $[-2^{63}, 2^{64}-1]$, as well as floating-point numbers are stored as `double`. This also concurs with the specification above. ### Zeros The JSON number grammar allows for different ways to express zero, and this library will store zeros differently: | Literal | Stored value and type | Serialization | |---------|------------------------|---------------| | `0` | `#!c std::uint64_t(0)` | `0` | | `-0` | `#!c std::int64_t(0)` | `0` | | `0.0` | `#!c double(0.0)` | `0.0` | | `-0.0` | `#!c double(-0.0)` | `-0.0` | | `0E0` | `#!c double(0.0)` | `0.0` | | `-0E0` | `#!c double(-0.0)` | `-0.0` | That is, `-0` is stored as a signed integer, but the serialization does not reproduce the `-`. ### Number serialization - Integer numbers are serialized as is; that is, no scientific notation is used. - Floating-point numbers are serialized as specified by the `#!c %g` printf modifier with [`std::numeric_limits<double>::max_digits10`](https://en.cppreference.com/w/cpp/types/numeric_limits/max_digits10) significant digits. The rationale is to use the shortest representation while still allow round-tripping. !!! hint "Notes regarding precision of floating-point numbers" As described above, floating-point numbers are rounded to the nearest double and serialized with the shortest representation to allow round-tripping. This can yield confusing examples: - The serialization can have fewer decimal places than the input: `#!c 2555.5599999999999` will be serialized as `#!c 2555.56`. The reverse can also be true. - The serialization can be in scientific notation even if the input is not: `#!c 0.0000972439793401814` will be serialized as `#!c 9.72439793401814e-05`. The reverse can also be true: `#!c 12345E-5` will be serialized as `#!c 0.12345`. - Conversions from `#!c float` to `#!c double` can also introduce rounding errors: ```cpp float f = 0.3; json j = f; std::cout << j << '\n'; ``` yields `#!c 0.30000001192092896`. All examples here can be reproduced by passing the original double value to ```cpp std::printf("%.*g\n", std::numeric_limits<double>::max_digits10, double_value); ``` #### NaN handling NaN (not-a-number) cannot be expressed with the number syntax described above and are in fact explicitly excluded: !!! quote "[RFC 8259](https://tools.ietf.org/html/rfc8259#section-6), Section 6" Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. That is, there is no way to *parse* a NaN value. However, NaN values can be stored in a JSON value by assignment. This library serializes NaN values as `#!js null`. This corresponds to the behavior of JavaScript's [`JSON.stringify`](https://www.w3schools.com/js/js_json_stringify.asp) function. !!! example The following example shows how a NaN value is stored in a `json` value. ```cpp int main() { double val = std::numeric_limits<double>::quiet_NaN(); std::cout << "val=" << val << std::endl; json j = val; std::cout << "j=" << j.dump() << std::endl; val = j; std::cout << "val=" << val << std::endl; } ``` output: ``` val=nan j=null val=nan ``` ### Number comparison Floating-point inside JSON values numbers are compared with `#!c json::number_float_t::operator==` which is `#!c double::operator==` by default. !!! example "Alternative comparison functions" To compare floating-point while respecting an epsilon, an alternative [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39) could be used, for instance ```cpp template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type> inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept { return std::abs(a - b) <= epsilon; } ``` Or you can self-define an operator equal function like this: ```cpp bool my_equal(const_reference lhs, const_reference rhs) { const auto lhs_type lhs.type(); const auto rhs_type rhs.type(); if (lhs_type == rhs_type) { switch(lhs_type) { // self_defined case case value_t::number_float: return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon(); // other cases remain the same with the original ... } } ... } ``` (see [#703](https://github.com/nlohmann/json/issues/703) for more information.) !!! note NaN values never compare equal to themselves or to other NaN values. See [#514](https://github.com/nlohmann/json/issues/514). ### Number conversion Just like the C++ language itself, the `get` family of functions allows conversions between unsigned and signed integers, and between integers and floating-point values to integers. This behavior may be surprising. !!! warning "Unconditional number conversions" ```cpp hl_lines="3" double d = 42.3; // non-integer double value 42.3 json jd = d; // stores double value 42.3 std::int64_t i = jd.template get<std::int64_t>(); // now i==42; no warning or error is produced ``` Note the last line with throw a [`json.exception.type_error.302`](../../home/exceptions.md#jsonexceptiontype_error302) exception if `jd` is not a numerical type, for instance a string. The rationale is twofold: 1. JSON does not define a number type or precision (see [#json-specification](above)). 2. C++ also allows to silently convert between number types. !!! success "Conditional number conversion" The code above can be solved by explicitly checking the nature of the value with members such as [`is_number_integer()`](../../api/basic_json/is_number_integer.md) or [`is_number_unsigned()`](../../api/basic_json/is_number_unsigned.md): ```cpp hl_lines="2" // check if jd is really integer-valued if (jd.is_number_integer()) { // if so, do the conversion and use i std::int64_t i = jd.template get<std::int64_t>(); // ... } else { // otherwise, take appropriate action // ... } ``` Note this approach also has the advantage that it can react on non-numerical JSON value types such as strings. (Example taken from [#777](https://github.com/nlohmann/json/issues/777#issuecomment-459968458).) ### Determine number types As the example in [Number conversion](#number-conversion) shows, there are different functions to determine the type of the stored number: - [`is_number()`](../../api/basic_json/is_number.md) returns `#!c true` for any number type - [`is_number_integer()`](../../api/basic_json/is_number_integer.md) returns `#!c true` for signed and unsigned integers - [`is_number_unsigned()`](../../api/basic_json/is_number_unsigned.md) returns `#!c true` for unsigned integers only - [`is_number_float()`](../../api/basic_json/is_number_float.md) returns `#!c true` for floating-point numbers - [`type_name()`](../../api/basic_json/type_name.md) returns `#!c "number"` for any number type - [`type()`](../../api/basic_json/type.md) returns a different enumerator of [`value_t`](../../api/basic_json/value_t.md) for all number types | function | unsigned integer | signed integer | floating-point | string | |----------------------------------------------------------------------|-------------------|------------------|----------------|----------------| | [`is_number()`](../../api/basic_json/is_number.md) | `#!c true` | `#!c true` | `#!c true` | `#!c false` | | [`is_number_integer()`](../../api/basic_json/is_number_integer.md) | `#!c true` | `#!c true` | `#!c false` | `#!c false` | | [`is_number_unsigned()`](../../api/basic_json/is_number_unsigned.md) | `#!c true` | `#!c false` | `#!c false` | `#!c false` | | [`is_number_float()`](../../api/basic_json/is_number_float.md) | `#!c false` | `#!c false` | `#!c true` | `#!c false` | | [`type_name()`](../../api/basic_json/type_name.md) | `#!c "number"` | `#!c "number"` | `#!c "number"` | `#!c "string"` | | [`type()`](../../api/basic_json/type.md) | `number_unsigned` | `number_integer` | `number_float` | `string` | ### Template number types The number types can be changed with template parameters. | position | number type | default type | possible values | |----------|-------------------|---------------------|------------------------------------------------| | 5 | signed integers | `#!c std::int64_t` | `#!c std::int32_t`, `#!c std::int16_t`, etc. | | 6 | unsigned integers | `#!c std::uint64_t` | `#!c std::uint32_t`, `#!c std::uint16_t`, etc. | | 7 | floating-point | `#!c double` | `#!c float`, `#!c long double` | !!! info "Constraints on number types" - The type for signed integers must be convertible from `#!c long long`. The type for floating-point numbers is used in case of overflow. - The type for unsigned integers must be convertible from `#!c unsigned long long`. The type for floating-point numbers is used in case of overflow. - The types for signed and unsigned integers must be distinct, see [#2573](https://github.com/nlohmann/json/issues/2573). - Only `#!c double`, `#!c float`, and `#!c long double` are supported for floating-point numbers. !!! example A `basic_json` type that uses `#!c long double` as floating-point type. ```cpp hl_lines="2" using json_ld = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, long double>; ``` Note values should then be parsed with `json_ld::parse` rather than `json::parse` as the latter would parse floating-point values to `#!c double` before then converting them to `#!c long double`.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/types/index.md
.md
12,701
270
# Types This page gives an overview how JSON values are stored and how this can be configured. ## Overview By default, JSON values are stored as follows: | JSON type | C++ type | |-----------|-----------------------------------------------| | object | `std::map<std::string, basic_json>` | | array | `std::vector<basic_json>` | | null | `std::nullptr_t` | | string | `std::string` | | boolean | `bool` | | number | `std::int64_t`, `std::uint64_t`, and `double` | Note there are three different types for numbers - when parsing JSON text, the best fitting type is chosen. ## Storage ```plantuml enum value_t { null object array string boolean number_integer number_unsigned number_float binary discarded } class json_value << (U,orchid) >> { object_t* object array_t* array string_t* string binary_t* binary boolean_t boolean number_integer_t number_integer number_unsigned_t number_unsigned number_float_t number_float } class basic_json { -- type and value -- value_t m_type json_value m_value -- derived types -- + <u>typedef</u> object_t + <u>typedef</u> array_t + <u>typedef</u> binary_t + <u>typedef</u> boolean_t + <u>typedef</u> number_integer_t + <u>typedef</u> number_unsigned_t + <u>typedef</u> number_float_t } basic_json .. json_value basic_json .. value_t ``` ## Template arguments The data types to store a JSON value are derived from the template arguments passed to class `basic_json`: ```cpp 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 basic_json; ``` Type `json` is an alias for `basic_json<>` and uses the default types. From the template arguments, the following types are derived: ```cpp using object_comparator_t = std::less<>; using object_t = ObjectType<StringType, basic_json, object_comparator_t, AllocatorType<std::pair<const StringType, basic_json>>>; using array_t = ArrayType<basic_json, AllocatorType<basic_json>>; using string_t = StringType; using boolean_t = BooleanType; using number_integer_t = NumberIntegerType; using number_unsigned_t = NumberUnsignedType; using number_float_t = NumberFloatType; using binary_t = nlohmann::byte_container_with_subtype<BinaryType>; ``` ## Objects [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON objects as follows: > An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array. ### Default type With the default values for *ObjectType* (`std::map`), *StringType* (`std::string`), and *AllocatorType* (`std::allocator`), the default value for `object_t` is: ```cpp std::map< std::string, // key_type basic_json, // value_type std::less<>, // key_compare std::allocator<std::pair<const std::string, basic_json>> // allocator_type > ``` ### Behavior The choice of `object_t` influences the behavior of the JSON class. With the default type, objects have the following behavior: - When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. - When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, `#!json {"key": 2, "key": 1}` could be equal to either `#!json {"key": 1}` or `#!json {"key": 2}`. - Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see `dump`) in this order. For instance, both `#!json {"b": 1, "a": 2}` and `#!json {"a": 2, "b": 1}` will be stored and serialized as `#!json {"a": 2, "b": 1}`. - When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, `#!json {"b": 1, "a": 2}` and `#!json {"a": 2, "b": 1}` will be treated as equal. ### Key order The order name/value pairs are added to the object is *not* preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as `std::map` with `std::less` is used by default. Please note this behavior conforms to [RFC 8259](https://tools.ietf.org/html/rfc8259), because any order implements the specified "unordered" nature of JSON objects. ### Limits [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the `max_size` function of a JSON object. ### Storage Objects are stored as pointers in a `basic_json` type. That is, for any access to object values, a pointer of type `object_t*` must be dereferenced. ## Arrays [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON arrays as follows: > An array is an ordered sequence of zero or more values. ### Default type With the default values for *ArrayType* (`std::vector`) and *AllocatorType* (`std::allocator`), the default value for `array_t` is: ```cpp std::vector< basic_json, // value_type std::allocator<basic_json> // allocator_type > ``` ### Limits [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the `max_size` function of a JSON array. ### Storage Arrays are stored as pointers in a `basic_json` type. That is, for any access to array values, a pointer of type `array_t*` must be dereferenced. ## Strings [RFC 8259](https://tools.ietf.org/html/rfc8259) describes JSON strings as follows: > A string is a sequence of zero or more Unicode characters. Unicode values are split by the JSON class into byte-sized characters during deserialization. ### Default type With the default values for *StringType* (`std::string`), the default value for `string_t` is `#!cpp std::string`. ### Encoding Strings are stored in UTF-8 encoding. Therefore, functions like `std::string::size()` or `std::string::length()` return the number of **bytes** in the string rather than the number of characters or glyphs. ### String comparison [RFC 8259](https://tools.ietf.org/html/rfc8259) states: > Software implementations are typically required to test names of object members for equality. Implementations that transform the textual representation into sequences of Unicode code units and then perform the comparison numerically, code unit by code unit, are interoperable in the sense that implementations will agree in all cases on equality or inequality of two strings. For example, implementations that compare strings with escaped characters unconverted may incorrectly find that `"a\\b"` and `"a\u005Cb"` are not equal. This implementation is interoperable as it does compare strings code unit by code unit. ### Storage String values are stored as pointers in a `basic_json` type. That is, for any access to string values, a pointer of type `string_t*` must be dereferenced. ## Booleans [RFC 8259](https://tools.ietf.org/html/rfc8259) implicitly describes a boolean as a type which differentiates the two literals `true` and `false`. ### Default type With the default values for *BooleanType* (`#!cpp bool`), the default value for `boolean_t` is `#!cpp bool`. ### Storage Boolean values are stored directly inside a `basic_json` type. ## Numbers See the [number handling](number_handling.md) article for a detailed discussion on how numbers are handled by this library. [RFC 8259](https://tools.ietf.org/html/rfc8259) describes numbers as follows: > The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed. (...) Numeric values that cannot be represented in the grammar below (such as Infinity and NaN) are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, `number_integer_t`, `number_unsigned_t`, and `number_float_t` are used. ### Default types With the default values for *NumberIntegerType* (`std::int64_t`), the default value for `number_integer_t` is `std::int64_t`. With the default values for *NumberUnsignedType* (`std::uint64_t`), the default value for `number_unsigned_t` is `std::uint64_t`. With the default values for *NumberFloatType* (`#!cpp double`), the default value for `number_float_t` is `#!cpp double`. ### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `#!c 010` will be serialized to `#!c 8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `#!json null`. ### Limits [RFC 8259](https://tools.ietf.org/html/rfc8259) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `#!c 9223372036854775807` (`INT64_MAX`) and the minimal integer number that can be stored is `#!c -9223372036854775808` (`INT64_MIN`). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as `number_unsigned_t` or `number_float_t`. When the default type is used, the maximal unsigned integer number that can be stored is `#!c 18446744073709551615` (`UINT64_MAX`) and the minimal integer number that can be stored is `#!c 0`. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as `number_integer_t` or `number_float_t`. [RFC 8259](https://tools.ietf.org/html/rfc8259) further states: > Note that when such software is used, numbers that are integers and are in the range $[-2^{53}+1, 2^{53}-1]$ are interoperable in the sense that implementations will agree exactly on their numeric values. As this range is a subrange of the exactly supported range [`INT64_MIN`, `INT64_MAX`], this class's integer type is interoperable. [RFC 8259](https://tools.ietf.org/html/rfc8259) states: > This specification allows implementations to set limits on the range and precision of numbers accepted. Since software that implements IEEE 754-2008 binary64 (double precision) numbers is generally available and widely used, good interoperability can be achieved by implementations that expect no more precision or range than these provide, in the sense that implementations will approximate JSON numbers within the expected precision. This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than `#!c -1.79769313486232e+308` and values greater than `#!c 1.79769313486232e+308` will be stored as NaN internally and be serialized to `#!json null`. ### Storage Integer number values, unsigned integer number values, and floating-point number values are stored directly inside a `basic_json` type.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/element_access/unchecked_access.md
.md
5,649
113
# Unchecked access: operator[] ## Overview Elements in a JSON object and a JSON array can be accessed via [`operator[]`](../../api/basic_json/operator%5B%5D.md) similar to a `#!cpp std::map` and a `#!cpp std::vector`, respectively. ??? example "Read access" Consider the following JSON value: ```json { "name": "Mary Smith", "age": 42, "hobbies": ["hiking", "reading"] } ``` Assume the value is parsed to a `json` variable `j`. | expression | value | |-------------------------|------------------------------------------------------------------------------| | `#!cpp j` | `#!json {"name": "Mary Smith", "age": 42, "hobbies": ["hiking", "reading"]}` | | `#!cpp j["name"]` | `#!json "Mary Smith"` | | `#!cpp j["age"]` | `#!json 42` | | `#!cpp j["hobbies"]` | `#!json ["hiking", "reading"]` | | `#!cpp j["hobbies"][0]` | `#!json "hiking"` | | `#!cpp j["hobbies"][1]` | `#!json "reading"` | The return value is a reference, so it can modify the original value. In case the passed object key is non-existing, a `#!json null` value is inserted which can be immediately be overwritten. ??? example "Write access" ```cpp j["name"] = "John Smith"; j["maidenName"] = "Jones"; ``` This code produces the following JSON value: ```json { "name": "John Smith", "maidenName": "Jones", "age": 42, "hobbies": ["hiking", "reading"] } ``` When accessing an invalid index (i.e., an index greater than or equal to the array size), the JSON array is resized such that the passed index is the new maximal index. Intermediate values are filled with `#!json null`. ??? example "Filling up arrays with `#!json null` values" ```cpp j["hobbies"][0] = "running"; j["hobbies"][3] = "cooking"; ``` This code produces the following JSON value: ```json { "name": "John Smith", "maidenName": "Jones", "age": 42, "hobbies": ["running", "reading", null, "cooking"] } ``` ## Notes !!! info "Design rationale" The library behaves differently to `#!cpp std::vector` and `#!cpp std::map`: - `#!cpp std::vector::operator[]` never inserts a new element. - `#!cpp std::map::operator[]` is not available for const values. The type `#!cpp json` wraps all JSON value types. It would be impossible to remove [`operator[]`](../../api/basic_json/operator%5B%5D.md) for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward `insert` calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects. !!! info The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown. !!! danger - It is **undefined behavior** to access a const object with a non-existing key. - It is **undefined behavior** to access a const array with an invalid index. - In debug mode, an **assertion** will fire in both cases. You can disable assertions by defining the preprocessor symbol `#!cpp NDEBUG` or redefine the macro [`JSON_ASSERT(x)`](../macros.md#json_assertx). See the documentation on [runtime assertions](../assertions.md) for more information. !!! failure "Exceptions" `operator[]` can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a [`basic_json::type_error`](../../home/exceptions.md#jsonexceptiontype_error305) is thrown. ## Summary | scenario | non-const value | const value | |-----------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------| | access to existing object key | reference to existing value is returned | const reference to existing value is returned | | access to valid array index | reference to existing value is returned | const reference to existing value is returned | | access to non-existing object key | reference to newly inserted `#!json null` value is returned | **undefined behavior**; [runtime assertion](../assertions.md) in debug mode | | access to invalid array index | reference to newly inserted `#!json null` value is returned; any index between previous maximal index and passed index are filled with `#!json null` | **undefined behavior**; [runtime assertion](../assertions.md) in debug mode |
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/element_access/index.md
.md
275
10
# Element Access There are many ways elements in a JSON value can be accessed: - unchecked access via [`operator[]`](unchecked_access.md) - checked access via [`at`](checked_access.md) - access with default value via [`value`](default_value.md) - iterators - JSON pointers
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/element_access/checked_access.md
.md
3,934
92
# Checked access: at ## Overview The [`at`](../../api/basic_json/at.md) member function performs checked access; that is, it returns a reference to the desired value if it exists and throws a [`basic_json::out_of_range` exception](../../home/exceptions.md#out-of-range) otherwise. ??? example "Read access" Consider the following JSON value: ```json { "name": "Mary Smith", "age": 42, "hobbies": ["hiking", "reading"] } ``` Assume the value is parsed to a `json` variable `j`. | expression | value | |-------------------------------|------------------------------------------------------------------------------| | `#!cpp j` | `#!json {"name": "Mary Smith", "age": 42, "hobbies": ["hiking", "reading"]}` | | `#!cpp j.at("name")` | `#!json "Mary Smith"` | | `#!cpp j.at("age")` | `#!json 42` | | `#!cpp j.at("hobbies")` | `#!json ["hiking", "reading"]` | | `#!cpp j.at("hobbies").at(0)` | `#!json "hiking"` | | `#!cpp j.at("hobbies").at(1)` | `#!json "reading"` | The return value is a reference, so it can be modified by the original value. ??? example "Write access" ```cpp j.at("name") = "John Smith"; ``` This code produces the following JSON value: ```json { "name": "John Smith", "age": 42, "hobbies": ["hiking", "reading"] } ``` When accessing an invalid index (i.e., an index greater than or equal to the array size) or the passed object key is non-existing, an exception is thrown. ??? example "Accessing via invalid index or missing key" ```cpp j.at("hobbies").at(3) = "cooking"; ``` This code produces the following exception: ``` [json.exception.out_of_range.401] array index 3 is out of range ``` When you [extended diagnostic messages](../../home/exceptions.md#extended-diagnostic-messages) are enabled by defining [`JSON_DIAGNOSTICS`](../../api/macros/json_diagnostics.md), the exception further gives information where the key or index is missing or out of range. ``` [json.exception.out_of_range.401] (/hobbies) array index 3 is out of range ``` ## Notes !!! failure "Exceptions" - [`at`](../../api/basic_json/at.md) can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a [`basic_json::type_error`](../../home/exceptions.md#jsonexceptiontype_error304) is thrown. - [`basic_json::out_of_range` exception](../../home/exceptions.md#out-of-range) exceptions are thrown if the provided key is not found in an object or the provided index is invalid. ## Summary | scenario | non-const value | const value | |-----------------------------------|------------------------------------------------|------------------------------------------------| | access to existing object key | reference to existing value is returned | const reference to existing value is returned | | access to valid array index | reference to existing value is returned | const reference to existing value is returned | | access to non-existing object key | `basic_json::out_of_range` exception is thrown | `basic_json::out_of_range` exception is thrown | | access to invalid array index | `basic_json::out_of_range` exception is thrown | `basic_json::out_of_range` exception is thrown |
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/element_access/default_value.md
.md
978
33
# Access with default value: value ## Overview In many situations such as configuration files, missing values are not exceptional, but may be treated as if a default value was present. ??? example Consider the following JSON value: ```json { "logOutput": "result.log", "append": true } ``` Assume the value is parsed to a `json` variable `j`. | expression | value | | ---------- | ----- | | `#!cpp j` | `#!json {"logOutput": "result.log", "append": true}` | | `#!cpp j.value("logOutput", "logfile.log")` | `#!json "result.log"` | | `#!cpp j.value("append", true)` | `#!json true` | | `#!cpp j.value("append", false)` | `#!json true` | | `#!cpp j.value("logLevel", "verbose")` | `#!json "verbose"` | ## Note !!! failure "Exceptions" - `value` can only be used with objects. For other types, a [`basic_json::type_error`](../../home/exceptions.md#jsonexceptiontype_error306) is thrown.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/parsing/parser_callbacks.md
.md
3,778
84
# Parser Callbacks ## Overview With a parser callback function, the result of parsing a JSON text can be influenced. When passed to `parse`, it is called on certain events (passed as `parse_event_t` via parameter `event`) with a set recursion depth `depth` and context JSON value `parsed`. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. The type of the callback function is: ```cpp template<typename BasicJsonType> using parser_callback_t = std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>; ``` ## Callback event types We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters `depth`, `event`, and `parsed`. | parameter `event` | description | parameter `depth` | parameter `parsed` | |-------------------------------|-----------------------------------------------------------|-------------------------------------------|----------------------------------| | `parse_event_t::object_start` | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded | | `parse_event_t::key` | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key | | `parse_event_t::object_end` | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object | | `parse_event_t::array_start` | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded | | `parse_event_t::array_end` | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array | | `parse_event_t::value` | the parser finished reading a JSON value | depth of the value | the parsed JSON value | ??? example When parsing the following JSON text, ```json { "name": "Berlin", "location": [ 52.519444, 13.406667 ] } ``` these calls are made to the callback function: | event | depth | parsed | | -------------- | ----- | ------ | | `object_start` | 0 | *discarded* | | `key` | 1 | `#!json "name"` | | `value` | 1 | `#!json "Berlin"` | | `key` | 1 | `#!json "location"` | | `array_start` | 1 | *discarded* | | `value` | 2 | `#!json 52.519444` | | `value` | 2 | `#!json 13.406667` | | `array_end` | 1 | `#!json [52.519444,13.406667]` | | `object_end` | 0 | `#!json {"location":[52.519444,13.406667],"name":"Berlin"}` | ## Return value Discarding a value (i.e., returning `#!c false`) has different effects depending on the context in which the function was called: - Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read. - In case a value outside a structured type is skipped, it is replaced with `#!json null`. This case happens if the top-level element is skipped. ??? example The example below demonstrates the `parse()` function with and without callback function. ```cpp --8<-- "examples/parse__string__parser_callback_t.cpp" ``` Output: ```json --8<-- "examples/parse__string__parser_callback_t.output" ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/parsing/parse_exceptions.md
.md
3,470
122
# Parsing and Exceptions When the input is not valid JSON, an exception of type [`parse_error`](../../home/exceptions.md#parse-errors) is thrown. This exception contains the position in the input where the error occurred, together with a diagnostic message and the last read input token. The exceptions page contains a [list of examples for parse error exceptions](../../home/exceptions.md#parse-errors). In case you process untrusted input, always enclose your code with a `#!cpp try`/`#!cpp catch` block, like ```cpp json j; try { j = json::parse(my_input); } catch (json::parse_error& ex) { std::cerr << "parse error at byte " << ex.byte << std::endl; } ``` In case exceptions are undesired or not supported by the environment, there are different ways to proceed: ## Switch off exceptions The `parse()` function accepts a `#!cpp bool` parameter `allow_exceptions` which controls whether an exception is thrown when a parse error occurs (`#!cpp true`, default) or whether a discarded value should be returned (`#!cpp false`). ```cpp json j = json::parse(my_input, nullptr, false); if (j.is_discarded()) { std::cerr << "parse error" << std::endl; } ``` Note there is no diagnostic information available in this scenario. ## Use accept() function Alternatively, function `accept()` can be used which does not return a `json` value, but a `#!cpp bool` indicating whether the input is valid JSON. ```cpp if (!json::accept(my_input)) { std::cerr << "parse error" << std::endl; } ``` Again, there is no diagnostic information available. ## User-defined SAX interface Finally, you can implement the [SAX interface](sax_interface.md) and decide what should happen in case of a parse error. This function has the following interface: ```cpp bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex); ``` The return value indicates whether the parsing should continue, so the function should usually return `#!cpp false`. ??? example ```cpp #include <iostream> #include "json.hpp" using json = nlohmann::json; class sax_no_exception : public nlohmann::detail::json_sax_dom_parser<json> { public: sax_no_exception(json& j) : nlohmann::detail::json_sax_dom_parser<json>(j, false) {} bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) { std::cerr << "parse error at input byte " << position << "\n" << ex.what() << "\n" << "last read: \"" << last_token << "\"" << std::endl; return false; } }; int main() { std::string myinput = "[1,2,3,]"; json result; sax_no_exception sax(result); bool parse_result = json::sax_parse(myinput, &sax); if (!parse_result) { std::cerr << "parsing unsuccessful!" << std::endl; } std::cout << "parsed value: " << result << std::endl; } ``` Output: ``` parse error at input byte 8 [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal last read: "3,]" parsing unsuccessful! parsed value: [1,2,3] ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/parsing/index.md
.md
159
14
# Parsing !!! note This page is under construction. ## Input ## SAX vs. DOM parsing ## Exceptions See [parsing and exceptions](parse_exceptions.md).
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/parsing/json_lines.md
.md
1,537
50
# JSON Lines The [JSON Lines](https://jsonlines.org) format is a text format of newline-delimited JSON. In particular: 1. The input must be UTF-8 encoded. 2. Every line must be a valid JSON value. 3. The line separator must be `\n`. As `\r` is silently ignored, `\r\n` is also supported. 4. The final character may be `\n`, but is not required to be one. !!! example "JSON Text example" ```json {"name": "Gilbert", "wins": [["straight", "7♣"], ["one pair", "10♥"]]} {"name": "Alexa", "wins": [["two pair", "4♠"], ["two pair", "9♠"]]} {"name": "May", "wins": []} {"name": "Deloise", "wins": [["three of a kind", "5♣"]]} ``` JSON Lines input with more than one value is treated as invalid JSON by the [`parse`](../../api/basic_json/parse.md) or [`accept`](../../api/basic_json/accept.md) functions. To process it line by line, functions like [`std::getline`](https://en.cppreference.com/w/cpp/string/basic_string/getline) can be used: !!! example "Example: Parse JSON Text input line by line" The example below demonstrates how JSON Lines can be processed. ```cpp --8<-- "examples/json_lines.cpp" ``` Output: ```json --8<-- "examples/json_lines.output" ``` !!! warning "Note" Using [`operator>>`](../../api/operator_gtgt.md) like ```cpp json j; while (input >> j) { std::cout << j << std::endl; } ``` with a JSON Lines input does not work, because the parser will try to parse one value after the last one.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/parsing/sax_interface.md
.md
3,290
74
# SAX Interface The library uses a SAX-like interface with the following functions: ```plantuml interface json::sax_t { + {abstract} bool null() + {abstract} bool boolean(bool val) + {abstract} bool number_integer(number_integer_t val) + {abstract} bool number_unsigned(number_unsigned_t val) + {abstract} bool number_float(number_float_t val, const string_t& s) + {abstract} bool string(string_t& val) + {abstract} bool binary(binary_t& val) + {abstract} bool start_object(std::size_t elements) + {abstract} bool end_object() + {abstract} bool start_array(std::size_t elements) + {abstract} bool end_array() + {abstract} bool key(string_t& val) + {abstract} bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) } ``` ```cpp // called when null is parsed bool null(); // called when a boolean is parsed; value is passed bool boolean(bool val); // called when a signed or unsigned integer number is parsed; value is passed bool number_integer(number_integer_t val); bool number_unsigned(number_unsigned_t val); // called when a floating-point number is parsed; value and original string is passed bool number_float(number_float_t val, const string_t& s); // called when a string is parsed; value is passed and can be safely moved away bool string(string_t& val); // called when a binary value is parsed; value is passed and can be safely moved away bool binary(binary& val); // called when an object or array begins or ends, resp. The number of elements is passed (or -1 if not known) bool start_object(std::size_t elements); bool end_object(); bool start_array(std::size_t elements); bool end_array(); // called when an object key is parsed; value is passed and can be safely moved away bool key(string_t& val); // called when a parse error occurs; byte position, the last token, and an exception is passed bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex); ``` The return value of each function determines whether parsing should proceed. To implement your own SAX handler, proceed as follows: 1. Implement the SAX interface in a class. You can use class `nlohmann::json_sax<json>` as base class, but you can also use any class where the functions described above are implemented and public. 2. Create an object of your SAX interface class, e.g. `my_sax`. 3. Call `#!cpp bool json::sax_parse(input, &my_sax);` where the first parameter can be any input like a string or an input stream and the second parameter is a pointer to your SAX interface. Note the `sax_parse` function only returns a `#!cpp bool` indicating the result of the last executed SAX event. It does not return `json` value - it is up to you to decide what to do with the SAX events. Furthermore, no exceptions are thrown in case of a parse error - it is up to you what to do with the exception object passed to your `parse_error` implementation. Internally, the SAX interface is used for the DOM parser (class `json_sax_dom_parser`) as well as the acceptor (`json_sax_acceptor`), see file `json_sax.hpp`. ## See also - [json_sax](../../api/json_sax/index.md) - documentation of the SAX interface - [sax_parse](../../api/basic_json/sax_parse.md) - SAX parser
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/binary_formats/bson.md
.md
4,127
97
# BSON BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays within other documents and arrays. BSON also contains extensions that allow representation of data types that are not part of the JSON spec. For example, BSON has a Date type and a BinData type. !!! abstract "References" - [BSON Website](http://bsonspec.org) - the main source on BSON - [BSON Specification](http://bsonspec.org/spec.html) - the specification ## Serialization The library uses the following mapping from JSON values types to BSON types: | JSON value type | value/range | BSON type | marker | |-----------------|-------------------------------------------|-----------|--------| | null | `null` | null | 0x0A | | boolean | `true`, `false` | boolean | 0x08 | | number_integer | -9223372036854775808..-2147483649 | int64 | 0x12 | | number_integer | -2147483648..2147483647 | int32 | 0x10 | | number_integer | 2147483648..9223372036854775807 | int64 | 0x12 | | number_unsigned | 0..2147483647 | int32 | 0x10 | | number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12 | | number_unsigned | 9223372036854775808..18446744073709551615 | -- | -- | | number_float | *any value* | double | 0x01 | | string | *any value* | string | 0x02 | | array | *any value* | document | 0x04 | | object | *any value* | document | 0x03 | | binary | *any value* | binary | 0x05 | !!! warning "Incomplete mapping" The mapping is **incomplete**, since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings. ??? example ```cpp --8<-- "examples/to_bson.cpp" ``` Output: ```c --8<-- "examples/to_bson.output" ``` ## Deserialization The library maps BSON record types to JSON value types as follows: | BSON type | BSON marker byte | JSON value type | |-----------------------|------------------|-----------------| | double | 0x01 | number_float | | string | 0x02 | string | | document | 0x03 | object | | array | 0x04 | array | | binary | 0x05 | binary | | undefined | 0x06 | *unsupported* | | ObjectId | 0x07 | *unsupported* | | boolean | 0x08 | boolean | | UTC Date-Time | 0x09 | *unsupported* | | null | 0x0A | null | | Regular Expr. | 0x0B | *unsupported* | | DB Pointer | 0x0C | *unsupported* | | JavaScript Code | 0x0D | *unsupported* | | Symbol | 0x0E | *unsupported* | | JavaScript Code | 0x0F | *unsupported* | | int32 | 0x10 | number_integer | | Timestamp | 0x11 | *unsupported* | | 128-bit decimal float | 0x13 | *unsupported* | | Max Key | 0x7F | *unsupported* | | Min Key | 0xFF | *unsupported* | !!! warning "Incomplete mapping" The mapping is **incomplete**. The unsupported mappings are indicated in the table above. ??? example ```cpp --8<-- "examples/from_bson.cpp" ``` Output: ```json --8<-- "examples/from_bson.output" ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/binary_formats/index.md
.md
2,733
53
# Binary Formats Though JSON is a ubiquitous data format, it is not a very compact format suitable for data exchange, for instance over a network. Hence, the library supports - [BJData](bjdata.md) (Binary JData), - [BSON](bson.md) (Binary JSON), - [CBOR](cbor.md) (Concise Binary Object Representation), - [MessagePack](messagepack.md), and - [UBJSON](ubjson.md) (Universal Binary JSON) to efficiently encode JSON values to byte vectors and to decode such vectors. ## Comparison ### Completeness | Format | Serialization | Deserialization | |-------------|-----------------------------------------------|----------------------------------------------| | BJData | complete | complete | | BSON | incomplete: top-level value must be an object | incomplete, but all JSON types are supported | | CBOR | complete | incomplete, but all JSON types are supported | | MessagePack | complete | complete | | UBJSON | complete | complete | ### Binary values | Format | Binary values | Binary subtypes | |-------------|---------------|-----------------| | BJData | not supported | not supported | | BSON | supported | supported | | CBOR | supported | supported | | MessagePack | supported | supported | | UBJSON | not supported | not supported | See [binary values](../binary_values.md) for more information. ### Sizes | Format | canada.json | twitter.json | citm_catalog.json | jeopardy.json | |--------------------|-------------|--------------|-------------------|---------------| | BJData | 53.2 % | 91.1 % | 78.1 % | 96.6 % | | BJData (size) | 58.6 % | 92.1 % | 86.7 % | 97.4 % | | BJData (size+tyoe) | 58.6 % | 92.1 % | 86.5 % | 97.4 % | | BSON | 85.8 % | 95.2 % | 95.8 % | 106.7 % | | CBOR | 50.5 % | 86.3 % | 68.4 % | 88.0 % | | MessagePack | 50.5 % | 86.0 % | 68.5 % | 87.9 % | | UBJSON | 53.2 % | 91.3 % | 78.2 % | 96.6 % | | UBJSON (size) | 58.6 % | 92.3 % | 86.8 % | 97.4 % | | UBJSON (size+type) | 55.9 % | 92.3 % | 85.0 % | 95.0 % | Sizes compared to minified JSON value.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/binary_formats/bjdata.md
.md
10,300
195
# BJData The [BJData format](https://neurojson.org) was derived from and improved upon [Universal Binary JSON(UBJSON)](https://ubjson.org) specification (Draft 12). Specifically, it introduces an optimized array container for efficient storage of N-dimensional packed arrays (**ND-arrays**); it also adds 4 new type markers - `[u] - uint16`, `[m] - uint32`, `[M] - uint64` and `[h] - float16` - to unambiguously map common binary numeric types; furthermore, it uses little-endian (LE) to store all numerics instead of big-endian (BE) as in UBJSON to avoid unnecessary conversions on commonly available platforms. Compared to other binary JSON-like formats such as MessagePack and CBOR, both BJData and UBJSON demonstrate a rare combination of being both binary and **quasi-human-readable**. This is because all semantic elements in BJData and UBJSON, including the data-type markers and name/string types are directly human-readable. Data stored in the BJData/UBJSON format are not only compact in size, fast to read/write, but also can be directly searched or read using simple processing. !!! abstract "References" - [BJData Specification](https://neurojson.org/bjdata/draft2) ## Serialization The library uses the following mapping from JSON values types to BJData types according to the BJData specification: | JSON value type | value/range | BJData type | marker | |-----------------|-------------------------------------------|----------------|--------| | null | `null` | null | `Z` | | boolean | `true` | true | `T` | | boolean | `false` | false | `F` | | number_integer | -9223372036854775808..-2147483649 | int64 | `L` | | number_integer | -2147483648..-32769 | int32 | `l` | | number_integer | -32768..-129 | int16 | `I` | | number_integer | -128..127 | int8 | `i` | | number_integer | 128..255 | uint8 | `U` | | number_integer | 256..32767 | int16 | `I` | | number_integer | 32768..65535 | uint16 | `u` | | number_integer | 65536..2147483647 | int32 | `l` | | number_integer | 2147483648..4294967295 | uint32 | `m` | | number_integer | 4294967296..9223372036854775807 | int64 | `L` | | number_integer | 9223372036854775808..18446744073709551615 | uint64 | `M` | | number_unsigned | 0..127 | int8 | `i` | | number_unsigned | 128..255 | uint8 | `U` | | number_unsigned | 256..32767 | int16 | `I` | | number_unsigned | 32768..65535 | uint16 | `u` | | number_unsigned | 65536..2147483647 | int32 | `l` | | number_unsigned | 2147483648..4294967295 | uint32 | `m` | | number_unsigned | 4294967296..9223372036854775807 | int64 | `L` | | number_unsigned | 9223372036854775808..18446744073709551615 | uint64 | `M` | | number_float | *any value* | float64 | `D` | | string | *with shortest length indicator* | string | `S` | | array | *see notes on optimized format/ND-array* | array | `[` | | object | *see notes on optimized format* | map | `{` | !!! success "Complete mapping" The mapping is **complete** in the sense that any JSON value type can be converted to a BJData value. Any BJData output created by `to_bjdata` can be successfully parsed by `from_bjdata`. !!! warning "Size constraints" The following values can **not** be converted to a BJData value: - strings with more than 18446744073709551615 bytes, i.e., $2^{64}-1$ bytes (theoretical) !!! info "Unused BJData markers" The following markers are not used in the conversion: - `Z`: no-op values are not created. - `C`: single-byte strings are serialized with `S` markers. !!! info "NaN/infinity handling" If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the `dump()` function which serializes NaN or Infinity to `#!json null`. !!! info "Endianness" A breaking difference between BJData and UBJSON is the endianness of numerical values. In BJData, all numerical data types (integers `UiuImlML` and floating-point values `hdD`) are stored in the little-endian (LE) byte order as opposed to big-endian as used by UBJSON. Adopting LE to store numeric records avoids unnecessary byte swapping on most modern computers where LE is used as the default byte order. !!! info "Optimized formats" Optimized formats for containers are supported via two parameters of [`to_bjdata`](../../api/basic_json/to_bjdata.md): - Parameter `use_size` adds size information to the beginning of a container and removes the closing marker. - Parameter `use_type` further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The `use_type` parameter must only be used together with `use_size = true`. Note that `use_size = true` alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed of the number of elements in the container. !!! info "ND-array optimized format" BJData extends UBJSON's optimized array **size** marker to support ND-arrays of uniform numerical data types (referred to as *packed arrays*). For example, the 2-D `uint8` integer array `[[1,2],[3,4],[5,6]]`, stored as nested optimized array in UBJSON `[ [$U#i2 1 2 [$U#i2 3 4 [$U#i2 5 6 ]`, can be further compressed in BJData to `[$U#[$i#i2 2 3 1 2 3 4 5 6` or `[$U#[i2 i3] 1 2 3 4 5 6`. To maintain type and size information, ND-arrays are converted to JSON objects following the **annotated array format** (defined in the [JData specification (Draft 3)][JDataAAFmt]), when parsed using [`from_bjdata`](../../api/basic_json/from_bjdata.md). For example, the above 2-D `uint8` array can be parsed and accessed as ```json { "_ArrayType_": "uint8", "_ArraySize_": [2,3], "_ArrayData_": [1,2,3,4,5,6] } ``` Likewise, when a JSON object in the above form is serialzed using [`to_bjdata`](../../api/basic_json/to_bjdata.md), it is automatically converted into a compact BJData ND-array. The only exception is, that when the 1-dimensional vector stored in `"_ArraySize_"` contains a single integer or two integers with one being 1, a regular 1-D optimized array is generated. The current version of this library does not yet support automatic detection of and conversion from a nested JSON array input to a BJData ND-array. [JDataAAFmt]: https://github.com/NeuroJSON/jdata/blob/master/JData_specification.md#annotated-storage-of-n-d-arrays) !!! info "Restrictions in optimized data types for arrays and objects" Due to diminished space saving, hampered readability, and increased security risks, in BJData, the allowed data types following the `$` marker in an optimized array and object container are restricted to **non-zero-fixed-length** data types. Therefore, the valid optimized type markers can only be one of `UiuImlMLhdDC`. This also means other variable (`[{SH`) or zero-length types (`TFN`) can not be used in an optimized array or object in BJData. !!! info "Binary values" If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the BJData documentation. In particular, this means that the serialization and the deserialization of JSON containing binary values into BJData and back will result in a different JSON object. ??? example ```cpp --8<-- "examples/to_bjdata.cpp" ``` Output: ```c --8<-- "examples/to_bjdata.output" ``` ## Deserialization The library maps BJData types to JSON value types as follows: | BJData type | JSON value type | marker | |-------------|-----------------------------------------|--------| | no-op | *no value, next value is read* | `N` | | null | `null` | `Z` | | false | `false` | `F` | | true | `true` | `T` | | float16 | number_float | `h` | | float32 | number_float | `d` | | float64 | number_float | `D` | | uint8 | number_unsigned | `U` | | int8 | number_integer | `i` | | uint16 | number_unsigned | `u` | | int16 | number_integer | `I` | | uint32 | number_unsigned | `m` | | int32 | number_integer | `l` | | uint64 | number_unsigned | `M` | | int64 | number_integer | `L` | | string | string | `S` | | char | string | `C` | | array | array (optimized values are supported) | `[` | | ND-array | object (in JData annotated array format)|`[$.#[.`| | object | object (optimized values are supported) | `{` | !!! success "Complete mapping" The mapping is **complete** in the sense that any BJData value can be converted to a JSON value. ??? example ```cpp --8<-- "examples/from_bjdata.cpp" ``` Output: ```json --8<-- "examples/from_bjdata.output" ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/binary_formats/cbor.md
.md
10,325
182
# CBOR The Concise Binary Object Representation (CBOR) is a data format whose design goals include the possibility of extremely small code size, fairly small message size, and extensibility without the need for version negotiation. !!! abstract "References" - [CBOR Website](http://cbor.io) - the main source on CBOR - [CBOR Playground](http://cbor.me) - an interactive webpage to translate between JSON and CBOR - [RFC 7049](https://tools.ietf.org/html/rfc7049) - the CBOR specification ## Serialization The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification ([RFC 7049](https://www.rfc-editor.org/rfc/rfc7049.html)): | JSON value type | value/range | CBOR type | first byte | |-----------------|--------------------------------------------|-----------------------------------|------------| | null | `null` | Null | 0xF6 | | boolean | `true` | True | 0xF5 | | boolean | `false` | False | 0xF4 | | number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B | | number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A | | number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39 | | number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38 | | number_integer | -24..-1 | Negative integer | 0x20..0x37 | | number_integer | 0..23 | Integer | 0x00..0x17 | | number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18 | | number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 | | number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A | | number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B | | number_unsigned | 0..23 | Integer | 0x00..0x17 | | number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18 | | number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 | | number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A | | number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B | | number_float | *any value representable by a float* | Single-Precision Float | 0xFA | | number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB | | string | *length*: 0..23 | UTF-8 string | 0x60..0x77 | | string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78 | | string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79 | | string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A | | string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B | | array | *size*: 0..23 | array | 0x80..0x97 | | array | *size*: 23..255 | array (1 byte follow) | 0x98 | | array | *size*: 256..65535 | array (2 bytes follow) | 0x99 | | array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A | | array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B | | object | *size*: 0..23 | map | 0xA0..0xB7 | | object | *size*: 23..255 | map (1 byte follow) | 0xB8 | | object | *size*: 256..65535 | map (2 bytes follow) | 0xB9 | | object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA | | object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB | | binary | *size*: 0..23 | byte string | 0x40..0x57 | | binary | *size*: 23..255 | byte string (1 byte follow) | 0x58 | | binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59 | | binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A | | binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B | Binary values with subtype are mapped to tagged values (0xD8..0xDB) depending on the subtype, followed by a byte string, see "binary" cells in the table above. !!! success "Complete mapping" The mapping is **complete** in the sense that any JSON value type can be converted to a CBOR value. !!! info "NaN/infinity handling" If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the normal JSON serialization which serializes NaN or Infinity to `null`. !!! info "Unused CBOR types" The following CBOR types are not used in the conversion: - UTF-8 strings terminated by "break" (0x7F) - arrays terminated by "break" (0x9F) - maps terminated by "break" (0xBF) - byte strings terminated by "break" (0x5F) - date/time (0xC0..0xC1) - bignum (0xC2..0xC3) - decimal fraction (0xC4) - bigfloat (0xC5) - expected conversions (0xD5..0xD7) - simple values (0xE0..0xF3, 0xF8) - undefined (0xF7) - half-precision floats (0xF9) - break (0xFF) !!! info "Tagged items" Binary subtypes will be serialized as tagged items. See [binary values](../binary_values.md#cbor) for an example. ??? example ```cpp --8<-- "examples/to_cbor.cpp" ``` Output: ```c --8<-- "examples/to_cbor.output" ``` ## Deserialization The library maps CBOR types to JSON value types as follows: | CBOR type | JSON value type | first byte | |------------------------|-----------------|------------| | Integer | number_unsigned | 0x00..0x17 | | Unsigned integer | number_unsigned | 0x18 | | Unsigned integer | number_unsigned | 0x19 | | Unsigned integer | number_unsigned | 0x1A | | Unsigned integer | number_unsigned | 0x1B | | Negative integer | number_integer | 0x20..0x37 | | Negative integer | number_integer | 0x38 | | Negative integer | number_integer | 0x39 | | Negative integer | number_integer | 0x3A | | Negative integer | number_integer | 0x3B | | Byte string | binary | 0x40..0x57 | | Byte string | binary | 0x58 | | Byte string | binary | 0x59 | | Byte string | binary | 0x5A | | Byte string | binary | 0x5B | | UTF-8 string | string | 0x60..0x77 | | UTF-8 string | string | 0x78 | | UTF-8 string | string | 0x79 | | UTF-8 string | string | 0x7A | | UTF-8 string | string | 0x7B | | UTF-8 string | string | 0x7F | | array | array | 0x80..0x97 | | array | array | 0x98 | | array | array | 0x99 | | array | array | 0x9A | | array | array | 0x9B | | array | array | 0x9F | | map | object | 0xA0..0xB7 | | map | object | 0xB8 | | map | object | 0xB9 | | map | object | 0xBA | | map | object | 0xBB | | map | object | 0xBF | | False | `false` | 0xF4 | | True | `true` | 0xF5 | | Null | `null` | 0xF6 | | Half-Precision Float | number_float | 0xF9 | | Single-Precision Float | number_float | 0xFA | | Double-Precision Float | number_float | 0xFB | !!! warning "Incomplete mapping" The mapping is **incomplete** in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors: - date/time (0xC0..0xC1) - bignum (0xC2..0xC3) - decimal fraction (0xC4) - bigfloat (0xC5) - expected conversions (0xD5..0xD7) - simple values (0xE0..0xF3, 0xF8) - undefined (0xF7) !!! warning "Object keys" CBOR allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected. !!! warning "Tagged items" Tagged items will throw a parse error by default. They can be ignored by passing `cbor_tag_handler_t::ignore` to function `from_cbor`. They can be stored by passing `cbor_tag_handler_t::store` to function `from_cbor`. ??? example ```cpp --8<-- "examples/from_cbor.cpp" ``` Output: ```json --8<-- "examples/from_cbor.output" ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/binary_formats/messagepack.md
.md
7,194
144
# MessagePack MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves. !!! abstract "References" - [MessagePack website](https://msgpack.org) - [MessagePack specification](https://github.com/msgpack/msgpack/blob/master/spec.md) ## Serialization The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification: | JSON value type | value/range | MessagePack type | first byte | |-----------------|------------------------------------------|------------------|------------| | null | `null` | nil | 0xC0 | | boolean | `true` | true | 0xC3 | | boolean | `false` | false | 0xC2 | | number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3 | | number_integer | -2147483648..-32769 | int32 | 0xD2 | | number_integer | -32768..-129 | int16 | 0xD1 | | number_integer | -128..-33 | int8 | 0xD0 | | number_integer | -32..-1 | negative fixint | 0xE0..0xFF | | number_integer | 0..127 | positive fixint | 0x00..0x7F | | number_integer | 128..255 | uint 8 | 0xCC | | number_integer | 256..65535 | uint 16 | 0xCD | | number_integer | 65536..4294967295 | uint 32 | 0xCE | | number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF | | number_unsigned | 0..127 | positive fixint | 0x00..0x7F | | number_unsigned | 128..255 | uint 8 | 0xCC | | number_unsigned | 256..65535 | uint 16 | 0xCD | | number_unsigned | 65536..4294967295 | uint 32 | 0xCE | | number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF | | number_float | *any value representable by a float* | float 32 | 0xCA | | number_float | *any value NOT representable by a float* | float 64 | 0xCB | | string | *length*: 0..31 | fixstr | 0xA0..0xBF | | string | *length*: 32..255 | str 8 | 0xD9 | | string | *length*: 256..65535 | str 16 | 0xDA | | string | *length*: 65536..4294967295 | str 32 | 0xDB | | array | *size*: 0..15 | fixarray | 0x90..0x9F | | array | *size*: 16..65535 | array 16 | 0xDC | | array | *size*: 65536..4294967295 | array 32 | 0xDD | | object | *size*: 0..15 | fix map | 0x80..0x8F | | object | *size*: 16..65535 | map 16 | 0xDE | | object | *size*: 65536..4294967295 | map 32 | 0xDF | | binary | *size*: 0..255 | bin 8 | 0xC4 | | binary | *size*: 256..65535 | bin 16 | 0xC5 | | binary | *size*: 65536..4294967295 | bin 32 | 0xC6 | !!! success "Complete mapping" The mapping is **complete** in the sense that any JSON value type can be converted to a MessagePack value. Any MessagePack output created by `to_msgpack` can be successfully parsed by `from_msgpack`. !!! warning "Size constraints" The following values can **not** be converted to a MessagePack value: - strings with more than 4294967295 bytes - byte strings with more than 4294967295 bytes - arrays with more than 4294967295 elements - objects with more than 4294967295 elements !!! info "NaN/infinity handling" If NaN or Infinity are stored inside a JSON number, they are serialized properly in contrast to the [dump](../../api/basic_json/dump.md) function which serializes NaN or Infinity to `null`. ??? example ```cpp --8<-- "examples/to_msgpack.cpp" ``` Output: ```c --8<-- "examples/to_msgpack.output" ``` ## Deserialization The library maps MessagePack types to JSON value types as follows: | MessagePack type | JSON value type | first byte | |------------------|-----------------|------------| | positive fixint | number_unsigned | 0x00..0x7F | | fixmap | object | 0x80..0x8F | | fixarray | array | 0x90..0x9F | | fixstr | string | 0xA0..0xBF | | nil | `null` | 0xC0 | | false | `false` | 0xC2 | | true | `true` | 0xC3 | | float 32 | number_float | 0xCA | | float 64 | number_float | 0xCB | | uint 8 | number_unsigned | 0xCC | | uint 16 | number_unsigned | 0xCD | | uint 32 | number_unsigned | 0xCE | | uint 64 | number_unsigned | 0xCF | | int 8 | number_integer | 0xD0 | | int 16 | number_integer | 0xD1 | | int 32 | number_integer | 0xD2 | | int 64 | number_integer | 0xD3 | | str 8 | string | 0xD9 | | str 16 | string | 0xDA | | str 32 | string | 0xDB | | array 16 | array | 0xDC | | array 32 | array | 0xDD | | map 16 | object | 0xDE | | map 32 | object | 0xDF | | bin 8 | binary | 0xC4 | | bin 16 | binary | 0xC5 | | bin 32 | binary | 0xC6 | | ext 8 | binary | 0xC7 | | ext 16 | binary | 0xC8 | | ext 32 | binary | 0xC9 | | fixext 1 | binary | 0xD4 | | fixext 2 | binary | 0xD5 | | fixext 4 | binary | 0xD6 | | fixext 8 | binary | 0xD7 | | fixext 16 | binary | 0xD8 | | negative fixint | number_integer | 0xE0-0xFF | !!! info Any MessagePack output created by `to_msgpack` can be successfully parsed by `from_msgpack`. ??? example ```cpp --8<-- "examples/from_msgpack.cpp" ``` Output: ```json --8<-- "examples/from_msgpack.output" ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/features/binary_formats/ubjson.md
.md
5,745
127
# UBJSON Universal Binary JSON (UBJSON) is a binary form directly imitating JSON, but requiring fewer bytes of data. It aims to achieve the generality of JSON, combined with being much easier to process than JSON. !!! abstract "References" - [UBJSON Website](http://ubjson.org) ## Serialization The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification: | JSON value type | value/range | UBJSON type | marker | |-----------------|-----------------------------------|----------------|--------| | null | `null` | null | `Z` | | boolean | `true` | true | `T` | | boolean | `false` | false | `F` | | number_integer | -9223372036854775808..-2147483649 | int64 | `L` | | number_integer | -2147483648..-32769 | int32 | `l` | | number_integer | -32768..-129 | int16 | `I` | | number_integer | -128..127 | int8 | `i` | | number_integer | 128..255 | uint8 | `U` | | number_integer | 256..32767 | int16 | `I` | | number_integer | 32768..2147483647 | int32 | `l` | | number_integer | 2147483648..9223372036854775807 | int64 | `L` | | number_unsigned | 0..127 | int8 | `i` | | number_unsigned | 128..255 | uint8 | `U` | | number_unsigned | 256..32767 | int16 | `I` | | number_unsigned | 32768..2147483647 | int32 | `l` | | number_unsigned | 2147483648..9223372036854775807 | int64 | `L` | | number_unsigned | 2147483649..18446744073709551615 | high-precision | `H` | | number_float | *any value* | float64 | `D` | | string | *with shortest length indicator* | string | `S` | | array | *see notes on optimized format* | array | `[` | | object | *see notes on optimized format* | map | `{` | !!! success "Complete mapping" The mapping is **complete** in the sense that any JSON value type can be converted to a UBJSON value. Any UBJSON output created by `to_ubjson` can be successfully parsed by `from_ubjson`. !!! warning "Size constraints" The following values can **not** be converted to a UBJSON value: - strings with more than 9223372036854775807 bytes (theoretical) !!! info "Unused UBJSON markers" The following markers are not used in the conversion: - `Z`: no-op values are not created. - `C`: single-byte strings are serialized with `S` markers. !!! info "NaN/infinity handling" If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the `dump()` function which serializes NaN or Infinity to `null`. !!! info "Optimized formats" The optimized formats for containers are supported: Parameter `use_size` adds size information to the beginning of a container and removes the closing marker. Parameter `use_type` further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The `use_type` parameter must only be used together with `use_size = true`. Note that `use_size = true` alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed on the number of elements of the container. !!! info "Binary values" If the JSON data contains the binary type, the value stored is a list of integers, as suggested by the UBJSON documentation. In particular, this means that serialization and the deserialization of a JSON containing binary values into UBJSON and back will result in a different JSON object. ??? example ```cpp --8<-- "examples/to_ubjson.cpp" ``` Output: ```c --8<-- "examples/to_ubjson.output" ``` ## Deserialization The library maps UBJSON types to JSON value types as follows: | UBJSON type | JSON value type | marker | |-------------|-----------------------------------------|--------| | no-op | *no value, next value is read* | `N` | | null | `null` | `Z` | | false | `false` | `F` | | true | `true` | `T` | | float32 | number_float | `d` | | float64 | number_float | `D` | | uint8 | number_unsigned | `U` | | int8 | number_integer | `i` | | int16 | number_integer | `I` | | int32 | number_integer | `l` | | int64 | number_integer | `L` | | string | string | `S` | | char | string | `C` | | array | array (optimized values are supported) | `[` | | object | object (optimized values are supported) | `{` | !!! success "Complete mapping" The mapping is **complete** in the sense that any UBJSON value can be converted to a JSON value. ??? example ```cpp --8<-- "examples/from_ubjson.cpp" ``` Output: ```json --8<-- "examples/from_ubjson.output" ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/integration/migration_guide.md
.md
8,377
265
# Migration Guide This page collects some guidelines on how to future-proof your code for future versions of this library. ## Replace deprecated functions The following functions have been deprecated and will be removed in the next major version (i.e., 4.0.0). All deprecations are annotated with [`HEDLEY_DEPRECATED_FOR`](https://nemequ.github.io/hedley/api-reference.html#HEDLEY_DEPRECATED_FOR) to report which function to use instead. #### Parsing - Function `friend std::istream& operator<<(basic_json&, std::istream&)` is deprecated since 3.0.0. Please use [`friend std::istream& operator>>(std::istream&, basic_json&)`](../api/operator_gtgt.md) instead. === "Deprecated" ```cpp nlohmann::json j; std::stringstream ss("[1,2,3]"); j << ss; ``` === "Future-proof" ```cpp nlohmann::json j; std::stringstream ss("[1,2,3]"); ss >> j; ``` - Passing iterator pairs or pointer/length pairs to parsing functions ([`parse`](../api/basic_json/parse.md), [`accept`](../api/basic_json/accept.md), [`sax_parse`](../api/basic_json/sax_parse.md), [`from_cbor`](../api/basic_json/from_cbor.md), [`from_msgpack`](../api/basic_json/from_msgpack.md), [`from_ubjson`](../api/basic_json/from_ubjson.md), and [`from_bson`](../api/basic_json/from_bson.md) via initializer lists is deprecated since 3.8.0. Instead, pass two iterators; for instance, call `from_cbor(ptr, ptr+len)` instead of `from_cbor({ptr, len})`. === "Deprecated" ```cpp const char* s = "[1,2,3]"; bool ok = nlohmann::json::accept({s, s + std::strlen(s)}); ``` === "Future-proof" ```cpp const char* s = "[1,2,3]"; bool ok = nlohmann::json::accept(s, s + std::strlen(s)); ``` #### JSON Pointers - Comparing JSON Pointers with strings via [`operator==`](../api/json_pointer/operator_eq.md) and [`operator!=`](../api/json_pointer/operator_ne.md) is deprecated since 3.11.2. To compare a [`json_pointer`](../api/json_pointer/index.md) `p` with a string `s`, convert `s` to a `json_pointer` first and use [`json_pointer::operator==`](../api/json_pointer/operator_eq.md) or [`json_pointer::operator!=`](../api/json_pointer/operator_ne.md). === "Deprecated" ```cpp nlohmann::json::json_pointer lhs("/foo/bar/1"); assert(lhs == "/foo/bar/1"); ``` === "Future-proof" ```cpp nlohmann::json::json_pointer lhs("/foo/bar/1"); assert(lhs == nlohmann::json::json_pointer("/foo/bar/1")); ``` - The implicit conversion from JSON Pointers to string ([`json_pointer::operator string_t`](../api/json_pointer/operator_string_t.md)) is deprecated since 3.11.0. Use [`json_pointer::to_string`](../api/json_pointer/to_string.md) instead. === "Deprecated" ```cpp nlohmann::json::json_pointer ptr("/foo/bar/1"); std::string s = ptr; ``` === "Future-proof" ```cpp nlohmann::json::json_pointer ptr("/foo/bar/1"); std::string s = ptr.to_string(); ``` - Passing a `basic_json` specialization as template parameter `RefStringType` to [`json_pointer`](../api/json_pointer/index.md) is deprecated since 3.11.0. The string type can now be directly provided. === "Deprecated" ```cpp using my_json = nlohmann::basic_json<std::map, std::vector, my_string_type>; nlohmann::json_pointer<my_json> ptr("/foo/bar/1"); ``` === "Future-proof" ```cpp nlohmann::json_pointer<my_string_type> ptr("/foo/bar/1"); ``` Thereby, `nlohmann::my_json::json_pointer` is an alias for `nlohmann::json_pointer<my_string_type>` and is always an alias to the `json_pointer` with the appropriate string type for all specializations of `basic_json`. #### Miscellaneous functions - The function `iterator_wrapper` is deprecated since 3.1.0. Please use the member function [`items`](../api/basic_json/items.md) instead. === "Deprecated" ```cpp for (auto &x : nlohmann::json::iterator_wrapper(j)) { std::cout << x.key() << ":" << x.value() << std::endl; } ``` === "Future-proof" ```cpp for (auto &x : j.items()) { std::cout << x.key() << ":" << x.value() << std::endl; } ``` - Function `friend std::ostream& operator>>(const basic_json&, std::ostream&)` is deprecated since 3.0.0. Please use [`friend operator<<(std::ostream&, const basic_json&)`](../api/operator_ltlt.md) instead. === "Deprecated" ```cpp j >> std::cout; ``` === "Future-proof" ```cpp std::cout << j; ``` - The legacy comparison behavior for discarded values is deprecated since 3.11.0. It is already disabled by default and can still be enabled by defining [`JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON`](../api/macros/json_use_legacy_discarded_value_comparison.md) to `1`. === "Deprecated" ```cpp #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 1 #include <nlohmann/json.hpp> ``` === "Future-proof" ```cpp #include <nlohmann/json.hpp> ``` ## Replace implicit conversions Implicit conversions via [`operator ValueType`](../api/basic_json/operator_ValueType.md) will be switched off by default in the next major release of the library. You can prepare existing code by already defining [`JSON_USE_IMPLICIT_CONVERSIONS`](../api/macros/json_use_implicit_conversions.md) to `0` and replace any implicit conversions with calls to [`get`](../api/basic_json/get.md), [`get_to`](../api/basic_json/get_to.md), [`get_ref`](../api/basic_json/get_ref.md), or [`get_ptr`](../api/basic_json/get_ptr.md). === "Deprecated" ```cpp nlohmann::json j = "Hello, world!"; std::string s = j; ``` === "Future-proof" ```cpp nlohmann::json j = "Hello, world!"; auto s = j.template get<std::string>(); ``` === "Future-proof (alternative)" ```cpp nlohmann::json j = "Hello, world!"; std::string s; j.get_to(s); ``` You can prepare existing code by already defining [`JSON_USE_IMPLICIT_CONVERSIONS`](../api/macros/json_use_implicit_conversions.md) to `0` and replace any implicit conversions with calls to [`get`](../api/basic_json/get.md). ## Import namespace `literals` for UDLs The user-defined string literals [`operator""_json`](../api/operator_literal_json.md) and [`operator""_json_pointer`](../api/operator_literal_json_pointer.md) will be removed from the global namespace in the next major release of the library. === "Deprecated" ```cpp nlohmann::json j = "[1,2,3]"_json; ``` === "Future-proof" ```cpp using namespace nlohmann::literals; nlohmann::json j = "[1,2,3]"_json; ``` To prepare existing code, define [`JSON_USE_GLOBAL_UDLS`](../api/macros/json_use_global_udls.md) to `0` and bring the string literals into scope where needed. ## Do not hard-code the complete library namespace The [`nlohmann` namespace](../features/namespace.md) contains a sub-namespace to avoid problems when different versions or configurations of the library are used in the same project. Always use `nlohmann` as namespace or, when the exact version and configuration is relevant, use macro [`NLOHMANN_JSON_NAMESPACE`](../api/macros/nlohmann_json_namespace.md) to denote the namespace. === "Dangerous" ```cpp void to_json(nlohmann::json_abi_v3_11_2::json& j, const person& p) { j["age"] = p.age; } ``` === "Future-proof" ```cpp void to_json(nlohmann::json& j, const person& p) { j["age"] = p.age; } ``` === "Future-proof (alternative)" ```cpp void to_json(NLOHMANN_JSON_NAMESPACE::json& j, const person& p) { j["age"] = p.age; } ``` ## Do not use the `details` namespace The `details` namespace is not part of the public API of the library and can change in any version without announcement. Do not rely on any function or type in the `details` namespace.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/integration/cmake.md
.md
6,497
173
# CMake ## Integration You can use the `nlohmann_json::nlohmann_json` interface target in CMake. This target populates the appropriate usage requirements for [`INTERFACE_INCLUDE_DIRECTORIES`](https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_INCLUDE_DIRECTORIES.html) to point to the appropriate include directories and [`INTERFACE_COMPILE_FEATURES`](https://cmake.org/cmake/help/latest/prop_tgt/INTERFACE_COMPILE_FEATURES.html) for the necessary C++11 flags. ### External To use this library from a CMake project, you can locate it directly with [`find_package()`](https://cmake.org/cmake/help/latest/command/find_package.html) and use the namespaced imported target from the generated package configuration: !!! example ```cmake title="CMakeLists.txt" cmake_minimum_required(VERSION 3.1) project(ExampleProject LANGUAGES CXX) find_package(nlohmann_json 3.11.2 REQUIRED) add_executable(example example.cpp) target_link_libraries(example PRIVATE nlohmann_json::nlohmann_json) ``` The package configuration file, `nlohmann_jsonConfig.cmake`, can be used either from an install tree or directly out of the build tree. ### Embedded To embed the library directly into an existing CMake project, place the entire source tree in a subdirectory and call `add_subdirectory()` in your `CMakeLists.txt` file. !!! example ```cmake title="CMakeLists.txt" cmake_minimum_required(VERSION 3.1) project(ExampleProject LANGUAGES CXX) # If you only include this third party in PRIVATE source files, you do not need to install it # when your main project gets installed. set(JSON_Install OFF CACHE INTERNAL "") add_subdirectory(nlohmann_json) add_executable(example example.cpp) target_link_libraries(example PRIVATE nlohmann_json::nlohmann_json) ``` !!! note Do not use `#!cmake include(nlohmann_json/CMakeLists.txt)`, since that carries with it unintended consequences that will break the build. It is generally discouraged (although not necessarily well documented as such) to use `#!cmake include(...)` for pulling in other CMake projects anyways. ### Supporting Both To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following. !!! example ```cmake title="CMakeLists.txt" project(ExampleProject LANGUAGES CXX) option(EXAMPLE_USE_EXTERNAL_JSON "Use an external JSON library" OFF) add_subdirectory(thirdparty) add_executable(example example.cpp) # Note that the namespaced target will always be available regardless of the import method target_link_libraries(example PRIVATE nlohmann_json::nlohmann_json) ``` ```cmake title="thirdparty/CMakeLists.txt" if(EXAMPLE_USE_EXTERNAL_JSON) find_package(nlohmann_json 3.11.2 REQUIRED) else() set(JSON_BuildTests OFF CACHE INTERNAL "") add_subdirectory(nlohmann_json) endif() ``` `thirdparty/nlohmann_json` is then a complete copy of this source tree. ### FetchContent Since CMake v3.11, [FetchContent](https://cmake.org/cmake/help/v3.11/module/FetchContent.html) can be used to automatically download a release as a dependency at configure type. !!! example ```cmake title="CMakeLists.txt" cmake_minimum_required(VERSION 3.11) project(ExampleProject LANGUAGES CXX) include(FetchContent) FetchContent_Declare(json URL https://github.com/nlohmann/json/releases/download/v3.11.2/json.tar.xz) FetchContent_MakeAvailable(json) add_executable(example example.cpp) target_link_libraries(example PRIVATE nlohmann_json::nlohmann_json) ``` !!! Note It is recommended to use the URL approach described above which is supported as of version 3.10.0. It is also possible to pass the Git repository like ```cmake FetchContent_Declare(json GIT_REPOSITORY https://github.com/nlohmann/json GIT_TAG v3.11.2 ) ``` However, the repository <https://github.com/nlohmann/json> download size is quite large. You might want to depend on a smaller repository. For instance, you might want to replace the URL in the example by <https://github.com/ArthurSonzogni/nlohmann_json_cmake_fetchcontent>. ## CMake Options ### `JSON_BuildTests` Build the unit tests when [`BUILD_TESTING`](https://cmake.org/cmake/help/latest/command/enable_testing.html) is enabled. This option is `ON` by default if the library's CMake project is the top project. That is, when integrating the library as described above, the test suite is not built unless explicitly switched on with this option. ### `JSON_CI` Enable CI build targets. The exact targets are used during the several CI steps and are subject to change without notice. This option is `OFF` by default. ### `JSON_Diagnostics` Enable [extended diagnostic messages](../home/exceptions.md#extended-diagnostic-messages) by defining macro [`JSON_DIAGNOSTICS`](../api/macros/json_diagnostics.md). This option is `OFF` by default. ### `JSON_DisableEnumSerialization` Disable default `enum` serialization by defining the macro [`JSON_DISABLE_ENUM_SERIALIZATION`](../api/macros/json_disable_enum_serialization.md). This option is `OFF` by default. ### `JSON_FastTests` Skip expensive/slow test suites. This option is `OFF` by default. Depends on `JSON_BuildTests`. ### `JSON_GlobalUDLs` Place user-defined string literals in the global namespace by defining the macro [`JSON_USE_GLOBAL_UDLS`](../api/macros/json_use_global_udls.md). This option is `OFF` by default. ### `JSON_ImplicitConversions` Enable implicit conversions by defining macro [`JSON_USE_IMPLICIT_CONVERSIONS`](../api/macros/json_use_implicit_conversions.md). This option is `ON` by default. ### `JSON_Install` Install CMake targets during install step. This option is `ON` by default if the library's CMake project is the top project. ### `JSON_MultipleHeaders` Use non-amalgamated version of the library. This option is `OFF` by default. ### `JSON_SystemInclude` Treat the library headers like system headers (i.e., adding `SYSTEM` to the [`target_include_directories`](https://cmake.org/cmake/help/latest/command/target_include_directories.html) call) to checks for this library by tools like Clang-Tidy. This option is `OFF` by default. ### `JSON_Valgrind` Execute test suite with [Valgrind](https://valgrind.org). This option is `OFF` by default. Depends on `JSON_BuildTests`.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/integration/package_managers.md
.md
9,835
199
# Package Managers Throughout this page, we will describe how to compile the example file `example.cpp` below. ```cpp --8<-- "integration/example.cpp" ``` When executed, this program should create output similar to ```json --8<-- "../../examples/meta.output" ``` ## Homebrew If you are using OS X and [Homebrew](http://brew.sh), just type ```sh brew install nlohmann-json ``` and you're set. If you want the bleeding edge rather than the latest release, use ```sh brew install nlohmann-json --HEAD ``` instead. See [nlohmann-json](https://formulae.brew.sh/formula/nlohmann-json) for more information. ??? example 1. Create the following file: ```cpp title="example.cpp" --8<-- "integration/example.cpp" ``` 2. Install the package ```sh brew install nlohmann-json ``` 3. Determine the include path, which defaults to `/usr/local/Cellar/nlohmann-json/$version/include`, where `$version` is the version of the library, e.g. `3.7.3`. The path of the library can be determined with ```sh brew list nlohmann-json ``` 4. Compile the code. For instance, the code can be compiled using Clang with ```sh clang++ example.cpp -I/usr/local/Cellar/nlohmann-json/3.7.3/include -std=c++11 -o example ``` :material-update: The [formula](https://formulae.brew.sh/formula/nlohmann-json) is updated automatically. ## Meson If you are using the [Meson Build System](http://mesonbuild.com), add this source tree as a [meson subproject](https://mesonbuild.com/Subprojects.html#using-a-subproject). You may also use the `include.zip` published in this project's [Releases](https://github.com/nlohmann/json/releases) to reduce the size of the vendored source tree. Alternatively, you can get a wrap file by downloading it from [Meson WrapDB](https://wrapdb.mesonbuild.com/nlohmann_json), or simply use `meson wrap install nlohmann_json`. Please see the meson project for any issues regarding the packaging. The provided `meson.build` can also be used as an alternative to cmake for installing `nlohmann_json` system-wide in which case a pkg-config file is installed. To use it, simply have your build system require the `nlohmann_json` pkg-config dependency. In Meson, it is preferred to use the [`dependency()`](https://mesonbuild.com/Reference-manual.html#dependency) object with a subproject fallback, rather than using the subproject directly. ## Bazel This repository provides a [Bazel](https://bazel.build/) `WORKSPACE.bazel` and a corresponding `BUILD.bazel` file. Therefore, this repository can be referenced by workspace rules such as `http_archive`, `git_repository`, or `local_repository` from other Bazel workspaces. To use the library you only need to depend on the target `@nlohmann_json//:json` (e.g. via `deps` attribute). ## Conan If you are using [Conan](https://www.conan.io/) to manage your dependencies, merely add `nlohmann_json/x.y.z` to your `conanfile`'s requires, where `x.y.z` is the release version you want to use. Please file issues [here](https://github.com/conan-io/conan-center-index/issues) if you experience problems with the packages. ??? example 1. Create the following files: ```ini title="Conanfile.txt" --8<-- "integration/conan/Conanfile.txt" ``` ```cmake title="CMakeLists.txt" --8<-- "integration/conan/CMakeLists.txt" ``` ```cpp title="example.cpp" --8<-- "integration/conan/example.cpp" ``` 2. Build: ```sh mkdir build cd build conan install .. cmake .. cmake --build . ``` :material-update: The [package](https://conan.io/center/nlohmann_json) is updated automatically. ## Spack If you are using [Spack](https://www.spack.io/) to manage your dependencies, you can use the [`nlohmann-json` package](https://spack.readthedocs.io/en/latest/package_list.html#nlohmann-json). Please see the [spack project](https://github.com/spack/spack) for any issues regarding the packaging. ## Hunter If you are using [hunter](https://github.com/cpp-pm/hunter) on your project for external dependencies, then you can use the [nlohmann_json package](https://hunter.readthedocs.io/en/latest/packages/pkg/nlohmann_json.html). Please see the hunter project for any issues regarding the packaging. ## Buckaroo If you are using [Buckaroo](https://buckaroo.pm), you can install this library's module with `buckaroo add github.com/buckaroo-pm/nlohmann-json`. Please file issues [here](https://github.com/buckaroo-pm/nlohmann-json). There is a demo repo [here](https://github.com/njlr/buckaroo-nholmann-json-example). ## vcpkg If you are using [vcpkg](https://github.com/Microsoft/vcpkg/) on your project for external dependencies, then you can install the [nlohmann-json package](https://github.com/Microsoft/vcpkg/tree/master/ports/nlohmann-json) with `vcpkg install nlohmann-json` and follow the then displayed descriptions. Please see the vcpkg project for any issues regarding the packaging. ??? example 1. Create the following files: ```cmake title="CMakeLists.txt" --8<-- "integration/vcpkg/CMakeLists.txt" ``` ```cpp title="example.cpp" --8<-- "integration/vcpkg/example.cpp" ``` 2. Install package: ```sh vcpkg install nlohmann-json ``` 3. Build: ```sh mkdir build cd build cmake .. -DCMAKE_TOOLCHAIN_FILE=/path/to/vcpkg/scripts/buildsystems/vcpkg.cmake cmake --build . ``` Note you need to adjust `/path/to/vcpkg/scripts/buildsystems/vcpkg.cmake` to your system. ## cget If you are using [cget](http://cget.readthedocs.io/en/latest/), you can install the latest development version with `cget install nlohmann/json`. A specific version can be installed with `cget install nlohmann/json@v3.1.0`. Also, the multiple header version can be installed by adding the `-DJSON_MultipleHeaders=ON` flag (i.e., `cget install nlohmann/json -DJSON_MultipleHeaders=ON`). :material-update: cget reads directly from the [GitHub repository](https://github.com/nlohmann/json) and is always up-to-date. ## CocoaPods If you are using [CocoaPods](https://cocoapods.org), you can use the library by adding pod `"nlohmann_json", '~>3.1.2'` to your podfile (see [an example](https://bitbucket.org/benman/nlohmann_json-cocoapod/src/master/)). Please file issues [here](https://bitbucket.org/benman/nlohmann_json-cocoapod/issues?status=new&status=open). ## NuGet If you are using [NuGet](https://www.nuget.org), you can use the package [nlohmann.json](https://www.nuget.org/packages/nlohmann.json/). Please check [this extensive description](https://github.com/nlohmann/json/issues/1132#issuecomment-452250255) on how to use the package. Please file issues [here](https://github.com/hnkb/nlohmann-json-nuget/issues). ## Conda If you are using [conda](https://conda.io/), you can use the package [nlohmann_json](https://github.com/conda-forge/nlohmann_json-feedstock) from [conda-forge](https://conda-forge.org) executing `conda install -c conda-forge nlohmann_json`. Please file issues [here](https://github.com/conda-forge/nlohmann_json-feedstock/issues). ## MSYS2 If you are using [MSYS2](http://www.msys2.org/), you can use the [mingw-w64-nlohmann-json](https://packages.msys2.org/base/mingw-w64-nlohmann-json) package, just type `pacman -S mingw-w64-i686-nlohmann-json` or `pacman -S mingw-w64-x86_64-nlohmann-json` for installation. Please file issues [here](https://github.com/msys2/MINGW-packages/issues/new?title=%5Bnlohmann-json%5D) if you experience problems with the packages. :material-update: The [package](https://packages.msys2.org/base/mingw-w64-nlohmann-json) is updated automatically. ## MacPorts If you are using [MacPorts](https://ports.macports.org), execute `sudo port install nlohmann-json` to install the [nlohmann-json](https://ports.macports.org/port/nlohmann-json/) package. :material-update: The [package](https://ports.macports.org/port/nlohmann-json/) is updated automatically. ## build2 If you are using [`build2`](https://build2.org), you can use the [`nlohmann-json`](https://cppget.org/nlohmann-json) package from the public repository <http://cppget.org> or directly from the [package's sources repository](https://github.com/build2-packaging/nlohmann-json). In your project's `manifest` file, just add `depends: nlohmann-json` (probably with some [version constraints](https://build2.org/build2-toolchain/doc/build2-toolchain-intro.xhtml#guide-add-remove-deps)). If you are not familiar with using dependencies in `build2`, [please read this introduction](https://build2.org/build2-toolchain/doc/build2-toolchain-intro.xhtml). Please file issues [here](https://github.com/build2-packaging/nlohmann-json) if you experience problems with the packages. :material-update: The [package](https://cppget.org/nlohmann-json) is updated automatically. ## wsjcpp If you are using [`wsjcpp`](http://wsjcpp.org), you can use the command `wsjcpp install "https://github.com/nlohmann/json:develop"` to get the latest version. Note you can change the branch ":develop" to an existing tag or another branch. :material-update: wsjcpp reads directly from the [GitHub repository](https://github.com/nlohmann/json) and is always up-to-date. ## CPM.cmake If you are using [`CPM.cmake`](https://github.com/TheLartians/CPM.cmake), you can check this [`example`](https://github.com/TheLartians/CPM.cmake/tree/master/examples/json). After [adding CPM script](https://github.com/TheLartians/CPM.cmake#adding-cpm) to your project, implement the following snippet to your CMake: ```cmake CPMAddPackage( NAME nlohmann_json GITHUB_REPOSITORY nlohmann/json VERSION 3.9.1) ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/integration/index.md
.md
637
19
# Header only [`json.hpp`](https://github.com/nlohmann/json/blob/develop/single_include/nlohmann/json.hpp) is the single required file in `single_include/nlohmann` or [released here](https://github.com/nlohmann/json/releases). You need to add ```cpp #include <nlohmann/json.hpp> // for convenience using json = nlohmann::json; ``` to the files you want to process JSON and set the necessary switches to enable C++11 (e.g., `-std=c++11` for GCC and Clang). You can further use file [`single_include/nlohmann/json_fwd.hpp`](https://github.com/nlohmann/json/blob/develop/single_include/nlohmann/json_fwd.hpp) for forward declarations.
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/integration/example.cpp
.cpp
174
11
#include <nlohmann/json.hpp> #include <iostream> #include <iomanip> using json = nlohmann::json; int main() { std::cout << std::setw(4) << json::meta() << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/integration/pkg-config.md
.md
405
14
# Pkg-config If you are using bare Makefiles, you can use `pkg-config` to generate the include flags that point to where the library is installed: ```sh pkg-config nlohmann_json --cflags ``` Users of the [Meson build system](package_managers.md#meson) will also be able to use a system-wide library, which will be found by `pkg-config`: ```meson json = dependency('nlohmann_json', required: true) ```
Markdown
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/integration/vcpkg/example.cpp
.cpp
139
10
#include <nlohmann/json.hpp> #include <iostream> using json = nlohmann::json; int main() { std::cout << json::meta() << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/docs/integration/conan/example.cpp
.cpp
139
10
#include <nlohmann/json.hpp> #include <iostream> using json = nlohmann::json; int main() { std::cout << json::meta() << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/mkdocs/scripts/check_structure.py
.py
8,453
180
#!/usr/bin/env python import glob import os.path import re import sys warnings = 0 def report(rule, location, description): global warnings warnings += 1 print(f'{warnings:3}. {location}: {description} [{rule}]') def check_structure(): expected_sections = [ 'Template parameters', 'Specializations', 'Iterator invalidation', 'Requirements', 'Member types', 'Member functions', 'Member variables', 'Static functions', 'Non-member functions', 'Literals', 'Helper classes', 'Parameters', 'Return value', 'Exception safety', 'Exceptions', 'Complexity', 'Possible implementation', 'Default definition', 'Notes', 'Examples', 'See also', 'Version history' ] required_sections = [ 'Examples', 'Version history' ] files = sorted(glob.glob('api/**/*.md', recursive=True)) for file in files: with open(file) as file_content: section_idx = -1 # the index of the current h2 section existing_sections = [] # the list of h2 sections in the file in_initial_code_example = False # whether we are inside the first code example block previous_line = None # the previous read line h1sections = 0 # the number of h1 sections in the file last_overload = 0 # the last seen overload number in the code example documented_overloads = {} # the overloads that have been documented in the current block current_section = None # the name of the current section for lineno, original_line in enumerate(file_content.readlines()): line = original_line.strip() if line.startswith('# '): h1sections += 1 # there should only be one top-level title if h1sections > 1: report('structure/unexpected_section', f'{file}:{lineno+1}', f'unexpected top-level title "{line}"') h1sections = 1 # Overview pages should have a better title if line == '# Overview': report('style/title', f'{file}:{lineno+1}', 'overview pages should have a better title than "Overview"') # lines longer than 160 characters are bad (unless they are tables) if len(line) > 160 and '|' not in line: report('whitespace/line_length', f'{file}:{lineno+1} ({current_section})', f'line is too long ({len(line)} vs. 160 chars)') # sections in `<!-- NOLINT -->` comments are treated as present if line.startswith('<!-- NOLINT'): current_section = line.strip('<!-- NOLINT') current_section = current_section.strip(' -->') existing_sections.append(current_section) # check if sections are correct if line.startswith('## '): # before starting a new section, check if the previous one documented all overloads if current_section in documented_overloads and last_overload != 0: if len(documented_overloads[current_section]) > 0 and len(documented_overloads[current_section]) != last_overload: expected = list(range(1, last_overload+1)) undocumented = [x for x in expected if x not in documented_overloads[current_section]] unexpected = [x for x in documented_overloads[current_section] if x not in expected] if len(undocumented): report('style/numbering', f'{file}:{lineno} ({current_section})', f'undocumented overloads: {", ".join([f"({x})" for x in undocumented])}') if len(unexpected): report('style/numbering', f'{file}:{lineno} ({current_section})', f'unexpected overloads: {", ".join([f"({x})" for x in unexpected])}') current_section = line.strip('## ') existing_sections.append(current_section) if current_section in expected_sections: idx = expected_sections.index(current_section) if idx <= section_idx: report('structure/section_order', f'{file}:{lineno+1}', f'section "{current_section}" is in an unexpected order (should be before "{expected_sections[section_idx]}")') section_idx = idx else: if 'index.md' not in file: # index.md files may have a different structure report('structure/unknown_section', f'{file}:{lineno+1}', f'section "{current_section}" is not part of the expected sections') # collect the numbered items of the current section to later check if they match the number of overloads if last_overload != 0 and not in_initial_code_example: if len(original_line) and original_line[0].isdigit(): number = int(re.findall(r"^(\d+).", original_line)[0]) if current_section not in documented_overloads: documented_overloads[current_section] = [] documented_overloads[current_section].append(number) # code example if line == '```cpp' and section_idx == -1: in_initial_code_example = True if in_initial_code_example and line.startswith('//') and line not in ['// since C++20', '// until C++20']: # check numbering of overloads if any(map(str.isdigit, line)): number = int(re.findall(r'\d+', line)[0]) if number != last_overload + 1: report('style/numbering', f'{file}:{lineno+1}', f'expected number ({number}) to be ({last_overload +1 })') last_overload = number if any(map(str.isdigit, line)) and '(' not in line: report('style/numbering', f'{file}:{lineno+1}', f'number should be in parentheses: {line}') if line == '```' and in_initial_code_example: in_initial_code_example = False # consecutive blank lines are bad if line == '' and previous_line == '': report('whitespace/blank_lines', f'{file}:{lineno}-{lineno+1} ({current_section})', 'consecutive blank lines') # check that non-example admonitions have titles untitled_admonition = re.match(r'^(\?\?\?|!!!) ([^ ]+)$', line) if untitled_admonition and untitled_admonition.group(2) != 'example': report('style/admonition_title', f'{file}:{lineno} ({current_section})', f'"{untitled_admonition.group(2)}" admonitions should have a title') previous_line = line if 'index.md' not in file: # index.md files may have a different structure for required_section in required_sections: if required_section not in existing_sections: report('structure/missing_section', f'{file}:{lineno+1}', f'required section "{required_section}" was not found') def check_examples(): example_files = sorted(glob.glob('../../examples/*.cpp')) markdown_files = sorted(glob.glob('**/*.md', recursive=True)) # check if every example file is used in at least one markdown file for example_file in example_files: example_file = os.path.join('examples', os.path.basename(example_file)) found = False for markdown_file in markdown_files: content = ' '.join(open(markdown_file).readlines()) if example_file in content: found = True break if not found: report('examples/missing', f'{example_file}', 'example file is not used in any documentation file') if __name__ == '__main__': print(120 * '-') check_structure() check_examples() print(120 * '-') if warnings > 0: sys.exit(1)
Python
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/invalid_iterator.cpp
.cpp
469
22
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { try { // calling iterator::key() on non-object iterator json j = "string"; json::iterator it = j.begin(); auto k = it.key(); } catch (json::invalid_iterator& e) { // output exception information std::cout << "message: " << e.what() << '\n' << "exception id: " << e.id << std::endl; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator_literal_json_pointer.cpp
.cpp
297
15
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; int main() { json j = R"( {"hello": "world", "answer": 42} )"_json; auto val = j["/hello"_json_pointer]; std::cout << std::setw(2) << val << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/flatten.cpp
.cpp
598
33
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON value json j = { {"pi", 3.141}, {"happy", true}, {"name", "Niels"}, {"nothing", nullptr}, { "answer", { {"everything", 42} } }, {"list", {1, 0, 2}}, { "object", { {"currency", "USD"}, {"value", 42.99} } } }; // call flatten() std::cout << std::setw(4) << j.flatten() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator_spaceship__scalartype.c++20.cpp
.cpp
1,115
42
#include <compare> #include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; const char* to_string(const std::partial_ordering& po) { if (std::is_lt(po)) { return "less"; } else if (std::is_gt(po)) { return "greater"; } else if (std::is_eq(po)) { return "equivalent"; } return "unordered"; } int main() { using float_limits = std::numeric_limits<json::number_float_t>; constexpr auto nan = float_limits::quiet_NaN(); // create several JSON values json boolean = false; json number = 17; json string = "17"; // output values and comparisons std::cout << std::boolalpha << std::fixed; std::cout << boolean << " <=> " << true << " := " << to_string(boolean <=> true) << '\n'; // *NOPAD* std::cout << number << " <=> " << 17.0 << " := " << to_string(number <=> 17.0) << '\n'; // *NOPAD* std::cout << number << " <=> " << nan << " := " << to_string(number <=> nan) << '\n'; // *NOPAD* std::cout << string << " <=> " << 17 << " := " << to_string(string <=> 17) << '\n'; // *NOPAD* }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/json_pointer__operator_add.cpp
.cpp
491
24
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON pointer json::json_pointer ptr("/foo"); std::cout << "\"" << ptr << "\"\n"; // append a JSON Pointer ptr /= json::json_pointer("/bar/baz"); std::cout << "\"" << ptr << "\"\n"; // append a string ptr /= "fob"; std::cout << "\"" << ptr << "\"\n"; // append an array index ptr /= 42; std::cout << "\"" << ptr << "\"" << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/README.cpp
.cpp
753
40
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON object json j = { {"pi", 3.141}, {"happy", true}, {"name", "Niels"}, {"nothing", nullptr}, { "answer", { {"everything", 42} } }, {"list", {1, 0, 2}}, { "object", { {"currency", "USD"}, {"value", 42.99} } } }; // add new values j["new"]["key"]["value"] = {"another", "list"}; // count elements auto s = j.size(); j["size"] = s; // pretty print with indent of 4 spaces std::cout << std::setw(4) << j << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/basic_json__moveconstructor.cpp
.cpp
287
18
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON value json a = 23; // move contents of a to b json b(std::move(a)); // serialize the JSON arrays std::cout << a << '\n'; std::cout << b << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/other_error.cpp
.cpp
699
31
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; int main() { try { // executing a failing JSON Patch operation json value = R"({ "best_biscuit": { "name": "Oreo" } })"_json; json patch = R"([{ "op": "test", "path": "/best_biscuit/name", "value": "Choco Leibniz" }])"_json; value.patch(patch); } catch (json::other_error& e) { // output exception information std::cout << "message: " << e.what() << '\n' << "exception id: " << e.id << std::endl; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator__equal.cpp
.cpp
827
25
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create several JSON values json array_1 = {1, 2, 3}; json array_2 = {1, 2, 4}; json object_1 = {{"A", "a"}, {"B", "b"}}; json object_2 = {{"B", "b"}, {"A", "a"}}; json number_1 = 17; json number_2 = 17.000000000000001L; json string_1 = "foo"; json string_2 = "bar"; // output values and comparisons std::cout << std::boolalpha; std::cout << array_1 << " == " << array_2 << " " << (array_1 == array_2) << '\n'; std::cout << object_1 << " == " << object_2 << " " << (object_1 == object_2) << '\n'; std::cout << number_1 << " == " << number_2 << " " << (number_1 == number_2) << '\n'; std::cout << string_1 << " == " << string_2 << " " << (string_1 == string_2) << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator_array__size_type.cpp
.cpp
483
26
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON array json array = {1, 2, 3, 4, 5}; // output element at index 3 (fourth element) std::cout << array[3] << '\n'; // change last element to 6 array[array.size() - 1] = 6; // output changed array std::cout << array << '\n'; // write beyond array limit array[10] = 11; // output changed array std::cout << array << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/at__keytype_const.c++17.cpp
.cpp
987
45
#include <iostream> #include <string_view> #include <nlohmann/json.hpp> using namespace std::string_view_literals; using json = nlohmann::json; int main() { // create JSON object const json object = { {"the good", "il buono"}, {"the bad", "il cattivo"}, {"the ugly", "il brutto"} }; // output element with key "the ugly" using string_view std::cout << object.at("the ugly"sv) << '\n'; // exception type_error.304 try { // use at() with string_view on a non-object type const json str = "I am a string"; std::cout << str.at("the good"sv) << '\n'; } catch (json::type_error& e) { std::cout << e.what() << '\n'; } // exception out_of_range.401 try { // try to read from a nonexisting key using string_view std::cout << object.at("the fast"sv) << '\n'; } catch (json::out_of_range) { std::cout << "out of range" << '\n'; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator__ValueType.cpp
.cpp
1,425
61
#include <iostream> #include <unordered_map> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON value with different types json json_types = { {"boolean", true}, { "number", { {"integer", 42}, {"floating-point", 17.23} } }, {"string", "Hello, world!"}, {"array", {1, 2, 3, 4, 5}}, {"null", nullptr} }; // use implicit conversions bool v1 = json_types["boolean"]; int v2 = json_types["number"]["integer"]; short v3 = json_types["number"]["integer"]; float v4 = json_types["number"]["floating-point"]; int v5 = json_types["number"]["floating-point"]; std::string v6 = json_types["string"]; std::vector<short> v7 = json_types["array"]; std::unordered_map<std::string, json> v8 = json_types; // print the conversion results std::cout << v1 << '\n'; std::cout << v2 << ' ' << v3 << '\n'; std::cout << v4 << ' ' << v5 << '\n'; std::cout << v6 << '\n'; for (auto i : v7) { std::cout << i << ' '; } std::cout << "\n\n"; for (auto i : v8) { std::cout << i.first << ": " << i.second << '\n'; } // example for an exception try { bool v1 = json_types["string"]; } catch (json::type_error& e) { std::cout << e.what() << '\n'; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/to_cbor.cpp
.cpp
507
23
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; int main() { // create a JSON value json j = R"({"compact": true, "schema": 0})"_json; // serialize it to CBOR std::vector<std::uint8_t> v = json::to_cbor(j); // print the vector content for (auto& byte : v) { std::cout << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << " "; } std::cout << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/begin.cpp
.cpp
330
17
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create an array value json array = {1, 2, 3, 4, 5}; // get an iterator to the first element json::iterator it = array.begin(); // serialize the element that the iterator points to std::cout << *it << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator_array__object_t_key_type.cpp
.cpp
656
33
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create a JSON object json object = { {"one", 1}, {"two", 2}, {"three", 2.9} }; // output element with key "two" std::cout << object["two"] << "\n\n"; // change element with key "three" object["three"] = 3; // output changed array std::cout << std::setw(4) << object << "\n\n"; // mention nonexisting key object["four"]; // write to nonexisting key object["five"]["really"]["nested"] = true; // output changed object std::cout << std::setw(4) << object << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/cbor_tag_handler_t.cpp
.cpp
837
29
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // tagged byte string std::vector<std::uint8_t> vec = {{0xd8, 0x42, 0x44, 0xcA, 0xfe, 0xba, 0xbe}}; // cbor_tag_handler_t::error throws try { auto b_throw_on_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::error); } catch (json::parse_error& e) { std::cout << e.what() << std::endl; } // cbor_tag_handler_t::ignore ignores the tag auto b_ignore_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::ignore); std::cout << b_ignore_tag << std::endl; // cbor_tag_handler_t::store stores the tag as binary subtype auto b_store_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::store); std::cout << b_store_tag << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/merge_patch.cpp
.cpp
1,031
42
#include <iostream> #include <nlohmann/json.hpp> #include <iomanip> // for std::setw using json = nlohmann::json; using namespace nlohmann::literals; int main() { // the original document json document = R"({ "title": "Goodbye!", "author": { "givenName": "John", "familyName": "Doe" }, "tags": [ "example", "sample" ], "content": "This will be unchanged" })"_json; // the patch json patch = R"({ "title": "Hello!", "phoneNumber": "+01-123-456-7890", "author": { "familyName": null }, "tags": [ "example" ] })"_json; // apply the patch document.merge_patch(patch); // output original and patched document std::cout << std::setw(4) << document << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/basic_json__copyassignment.cpp
.cpp
283
19
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json a = 23; json b = 42; // copy-assign a to b b = a; // serialize the JSON arrays std::cout << a << '\n'; std::cout << b << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/array.cpp
.cpp
543
20
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON arrays json j_no_init_list = json::array(); json j_empty_init_list = json::array({}); json j_nonempty_init_list = json::array({1, 2, 3, 4}); json j_list_of_pairs = json::array({ {"one", 1}, {"two", 2} }); // serialize the JSON arrays std::cout << j_no_init_list << '\n'; std::cout << j_empty_init_list << '\n'; std::cout << j_nonempty_init_list << '\n'; std::cout << j_list_of_pairs << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator__lessequal.cpp
.cpp
825
25
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create several JSON values json array_1 = {1, 2, 3}; json array_2 = {1, 2, 4}; json object_1 = {{"A", "a"}, {"B", "b"}}; json object_2 = {{"B", "b"}, {"A", "a"}}; json number_1 = 17; json number_2 = 17.0000000000001L; json string_1 = "foo"; json string_2 = "bar"; // output values and comparisons std::cout << std::boolalpha; std::cout << array_1 << " <= " << array_2 << " " << (array_1 <= array_2) << '\n'; std::cout << object_1 << " <= " << object_2 << " " << (object_1 <= object_2) << '\n'; std::cout << number_1 << " <= " << number_2 << " " << (number_1 <= number_2) << '\n'; std::cout << string_1 << " <= " << string_2 << " " << (string_1 <= string_2) << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/json_pointer__string_t.cpp
.cpp
303
14
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { json::json_pointer::string_t s = "This is a string."; std::cout << s << std::endl; std::cout << std::boolalpha << std::is_same<json::json_pointer::string_t, json::string_t>::value << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/parse__iterator_pair.cpp
.cpp
423
16
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // a JSON text given an input with other values std::vector<std::uint8_t> input = {'[', '1', ',', '2', ',', '3', ']', 'o', 't', 'h', 'e', 'r'}; // parse and serialize JSON json j_complete = json::parse(input.begin(), input.begin() + 7); std::cout << std::setw(4) << j_complete << "\n\n"; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/is_structured.cpp
.cpp
1,001
31
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = 17; json j_number_float = 23.42; json j_number_unsigned_integer = 12345678987654321u; json j_object = {{"one", 1}, {"two", 2}}; json j_array = {1, 2, 4, 8, 16}; json j_string = "Hello, world"; json j_binary = json::binary({1, 2, 3}); // call is_structured() std::cout << std::boolalpha; std::cout << j_null.is_structured() << '\n'; std::cout << j_boolean.is_structured() << '\n'; std::cout << j_number_integer.is_structured() << '\n'; std::cout << j_number_unsigned_integer.is_structured() << '\n'; std::cout << j_number_float.is_structured() << '\n'; std::cout << j_object.is_structured() << '\n'; std::cout << j_array.is_structured() << '\n'; std::cout << j_string.is_structured() << '\n'; std::cout << j_binary.is_structured() << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/nlohmann_define_type_intrusive_with_default_macro.cpp
.cpp
1,126
43
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; namespace ns { class person { private: std::string name = "John Doe"; std::string address = "123 Fake St"; int age = -1; public: person() = default; person(std::string name_, std::string address_, int age_) : name(std::move(name_)), address(std::move(address_)), age(age_) {} NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(person, name, address, age) }; } // namespace ns int main() { ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60}; // serialization: person -> json json j = p; std::cout << "serialization: " << j << std::endl; // deserialization: json -> person json j2 = R"({"address": "742 Evergreen Terrace", "age": 40, "name": "Homer Simpson"})"_json; auto p2 = j2.template get<ns::person>(); // incomplete deserialization: json j3 = R"({"address": "742 Evergreen Terrace", "name": "Maggie Simpson"})"_json; auto p3 = j3.template get<ns::person>(); std::cout << "roundtrip: " << json(p3) << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/at__json_pointer.cpp
.cpp
2,471
105
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; int main() { // create a JSON value json j = { {"number", 1}, {"string", "foo"}, {"array", {1, 2}} }; // read-only access // output element with JSON pointer "/number" std::cout << j.at("/number"_json_pointer) << '\n'; // output element with JSON pointer "/string" std::cout << j.at("/string"_json_pointer) << '\n'; // output element with JSON pointer "/array" std::cout << j.at("/array"_json_pointer) << '\n'; // output element with JSON pointer "/array/1" std::cout << j.at("/array/1"_json_pointer) << '\n'; // writing access // change the string j.at("/string"_json_pointer) = "bar"; // output the changed string std::cout << j["string"] << '\n'; // change an array element j.at("/array/1"_json_pointer) = 21; // output the changed array std::cout << j["array"] << '\n'; // out_of_range.106 try { // try to use an array index with leading '0' json::reference ref = j.at("/array/01"_json_pointer); } catch (json::parse_error& e) { std::cout << e.what() << '\n'; } // out_of_range.109 try { // try to use an array index that is not a number json::reference ref = j.at("/array/one"_json_pointer); } catch (json::parse_error& e) { std::cout << e.what() << '\n'; } // out_of_range.401 try { // try to use an invalid array index json::reference ref = j.at("/array/4"_json_pointer); } catch (json::out_of_range& e) { std::cout << e.what() << '\n'; } // out_of_range.402 try { // try to use the array index '-' json::reference ref = j.at("/array/-"_json_pointer); } catch (json::out_of_range& e) { std::cout << e.what() << '\n'; } // out_of_range.403 try { // try to use a JSON pointer to a nonexistent object key json::const_reference ref = j.at("/foo"_json_pointer); } catch (json::out_of_range& e) { std::cout << e.what() << '\n'; } // out_of_range.404 try { // try to use a JSON pointer that cannot be resolved json::reference ref = j.at("/number/foo"_json_pointer); } catch (json::out_of_range& e) { std::cout << e.what() << '\n'; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/object_t.cpp
.cpp
231
11
#include <iostream> #include <iomanip> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { std::cout << std::boolalpha << std::is_same<std::map<json::string_t, json>, json::object_t>::value << std::endl; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/at__json_pointer_const.cpp
.cpp
1,952
81
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; using namespace nlohmann::literals; int main() { // create a JSON value const json j = { {"number", 1}, {"string", "foo"}, {"array", {1, 2}} }; // read-only access // output element with JSON pointer "/number" std::cout << j.at("/number"_json_pointer) << '\n'; // output element with JSON pointer "/string" std::cout << j.at("/string"_json_pointer) << '\n'; // output element with JSON pointer "/array" std::cout << j.at("/array"_json_pointer) << '\n'; // output element with JSON pointer "/array/1" std::cout << j.at("/array/1"_json_pointer) << '\n'; // out_of_range.109 try { // try to use an array index that is not a number json::const_reference ref = j.at("/array/one"_json_pointer); } catch (json::parse_error& e) { std::cout << e.what() << '\n'; } // out_of_range.401 try { // try to use an invalid array index json::const_reference ref = j.at("/array/4"_json_pointer); } catch (json::out_of_range& e) { std::cout << e.what() << '\n'; } // out_of_range.402 try { // try to use the array index '-' json::const_reference ref = j.at("/array/-"_json_pointer); } catch (json::out_of_range& e) { std::cout << e.what() << '\n'; } // out_of_range.403 try { // try to use a JSON pointer to a nonexistent object key json::const_reference ref = j.at("/foo"_json_pointer); } catch (json::out_of_range& e) { std::cout << e.what() << '\n'; } // out_of_range.404 try { // try to use a JSON pointer that cannot be resolved json::const_reference ref = j.at("/number/foo"_json_pointer); } catch (json::out_of_range& e) { std::cout << e.what() << '\n'; } }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/operator__notequal__nullptr_t.cpp
.cpp
698
23
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create several JSON values json array = {1, 2, 3}; json object = {{"A", "a"}, {"B", "b"}}; json number = 17; json string = "foo"; json null; // output values and comparisons std::cout << std::boolalpha; std::cout << array << " != nullptr " << (array != nullptr) << '\n'; std::cout << object << " != nullptr " << (object != nullptr) << '\n'; std::cout << number << " != nullptr " << (number != nullptr) << '\n'; std::cout << string << " != nullptr " << (string != nullptr) << '\n'; std::cout << null << " != nullptr " << (null != nullptr) << '\n'; }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/ordered_map.cpp
.cpp
1,109
44
#include <iostream> #include <nlohmann/json.hpp> // simple output function template<typename Map> void output(const char* prefix, const Map& m) { std::cout << prefix << " = { "; for (auto& element : m) { std::cout << element.first << ":" << element.second << ' '; } std::cout << "}" << std::endl; } int main() { // create and fill two maps nlohmann::ordered_map<std::string, std::string> m_ordered; m_ordered["one"] = "eins"; m_ordered["two"] = "zwei"; m_ordered["three"] = "drei"; std::map<std::string, std::string> m_std; m_std["one"] = "eins"; m_std["two"] = "zwei"; m_std["three"] = "drei"; // output: m_ordered is ordered by insertion order, m_std is ordered by key output("m_ordered", m_ordered); output("m_std", m_std); // erase and re-add "one" key m_ordered.erase("one"); m_ordered["one"] = "eins"; m_std.erase("one"); m_std["one"] = "eins"; // output: m_ordered shows newly added key at the end; m_std is again ordered by key output("m_ordered", m_ordered); output("m_std", m_std); }
C++
3D
OpenMS/OpenMS
src/openms/extern/nlohmann_json/docs/examples/nlohmann_json_namespace_no_version.cpp
.cpp
284
14
#include <iostream> #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 1 #include <nlohmann/json.hpp> // macro needed to output the NLOHMANN_JSON_NAMESPACE as string literal #define Q(x) #x #define QUOTE(x) Q(x) int main() { std::cout << QUOTE(NLOHMANN_JSON_NAMESPACE) << std::endl; }
C++