* Add element access, iteration, values, and JSON pointers to json_view Give basic_json_view the read-only access functions of basic_json: operator[] and at() with keys and indices, front()/back(), find(), contains(), count(), begin()/end() and cbegin()/cend(), items() with structured bindings from C++17 on, and type_name(). Exceptions have the ids and messages of the const functions of basic_json. Where basic_json has undefined behavior the view answers safely: operator[] with a missing key or an out-of-range index returns a discarded view, and front()/back() of an empty container throw invalid_iterator.214. Objects are iterated in document order, and all members are visited; duplicate-key lookups find the first member (as yyjson and simdjson do), while parse(), materialize(), and the map conversions keep the last value, as parse() does. Keys of up to 16 bytes are compared with two overlapping loads. Add value conversions: get<T>()/get_to() for arithmetic types, bool, nullptr_t, strings (std::basic_string copied, string_view_t without a copy), BasicJsonType, views, std::vector, and maps with string keys; get_string() for the string without a copy; number_token() for the number exactly as written in the source; value() with keys and JSON pointers; and operator[]/at()/ contains() with JSON pointers. Everything else, including types with from_json(), goes through materialize() of that subtree. get<T>() of arithmetic types is inlined down to the conversion, so reading an integer needs no call. detail::json_pointer_access exposes a pointer's reference tokens to code outside basic_json. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Make view lookups last-wins and chained access safe * Lookups (operator[], at, find, contains, count, value, JSON pointers) return the last member of a duplicate key, as materialize() and parse() keep it. * operator[] on a discarded view returns a discarded view instead of throwing, so v["a"]["b"] is safe for a missing "a". * operator[] and at() take any integer type (not only int and size_t), fixing ambiguous calls with unsigned, long, std::int64_t, ... * Fix the operator[] documentation, which claimed a discarded view for a type mismatch where type_error.305 is thrown. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Replace the removed operator bool of basic_json_view in the header and its tests A view is tested with is_discarded(); the lookups in at(), value() and contains(json_pointer) and the unit tests no longer rely on the explicit conversion to bool. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Use named documents in the json_view tests that called root() on a temporary root() of an rvalue document is deleted, because the views would dangle. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Test discarded views with is_discarded() in the operator[] docs and examples The explicit conversion to bool of basic_json_view is gone. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Return the first member of duplicate keys from lookups again Looking up the last member of a duplicate key cannot stop at a match, so every lookup scanned the whole object (1.6 to 3.4 times slower for small objects). operator[](key), at, find, value, contains, count, and JSON pointer resolution return the first member again, as yyjson and simdjson do; materialize() and get<map>() keep the last value, as parse(). The documentation says so in the feature page and on each lookup page, and explains how to get the value parse() would give. The integer index templates and the discarded chaining of operator[] stay. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Do not force-inline the view's functions on MSVC __forceinline makes MSVC report C4714 for function templates it cannot inline (get<std::string>), an error under /WX. The forced inlining is only a performance hint, so use plain inline there. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Make json_view.hpp pass include-what-you-use Mark the includes that are needed by design (json.hpp, the macro unscope, <tuple> for the tuple_size specialization), take size_t from <cstring>, and drop the forward declaration of basic_json_document that the friend declaration makes redundant. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Avoid GCC useless-cast warnings in the integer index tests Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Make json_view.hpp pass include-what-you-use ci_single_binaries runs IWYU with --error on every header. For json_view.hpp it suggested adding <array> (std::array is used), the headers that json.hpp already provides (abi_config, abi_macros, input_adapters, json_pointer, cpp_future, string_concat, value_t, json_fwd), and <version> for std::nullptr_t, and removing <cstddef>. - include <array> - keep <cstddef> (nullptr_t, size_t; IWYU attributes them to <version> and <cstring>) - tell IWYU not to suggest the headers that json.hpp provides: the amalgamated json_view.hpp only includes json.hpp, so including them here would duplicate their definitions Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Fix the clang-tidy 22 findings in json_view and its tests The same changes as on the dump branch, where they were first made, so that this branch passes clang-tidy on its own. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Regenerate the amalgamated headers Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Report one-character non-numeric array indices like basic_json in the view Develop's #5800 made basic_json report a JSON pointer array index such as "/a" as parse_error.109 instead of out_of_range.404, as longer ones were; the view's array_index() follows, with "-" and the empty token still unresolved. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Address the review of json_view element access From gregmarr's review of #5622: - count() counts every member with the key, so count(key) > 1 detects duplicate keys; it was contains() as 0/1 before. - get_to() passes types that get<T>() does not convert directly to from_json with the existing value, as basic_json::get_to() does, so that a from_json which sets only the fields present keeps the others. - array_index() checks the empty token and "-" first; the results are unchanged. - Docs: no "if an exception is thrown" where a view never changes anything; the borrowed source must also stay unmodified; items() on a temporary view is safe; back()/front() notes shortened; the basic_json see-also entries say how the view's results can differ. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Regenerate the amalgamated headers Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Count matching keys as unsigned in the json_view access test The conditional added 1 or 0 as int to a std::size_t, which GCC rejects with -Werror=sign-conversion (ci_test_standards_gcc). Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Address the second review round of json_view element access From gregmarr's review of #5622: - begin()/end(): "a null value or a discarded view iterates as an empty range", singular like the primitive case before it. - The class page's list of function groups has no trailing commas. - document_data::key_equals() compares a key node with a string, for the key comparisons that were spelled out in each lookup. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Regenerate the amalgamated headers Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Write the negated enable_if conditions of json_view with negation<> With a ! or && in the condition, astyle spaces the whole template header (template < ... >); detail::negation and a named trait keep it compact, as the library writes such conditions elsewhere. From gregmarr's review of #5630. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Regenerate the amalgamated headers Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Keep detail::negation out of json_view.hpp's enable_ifs include-what-you-use asks json_view.hpp to include detail/meta/type_traits.hpp for it, which the single header must not do (the amalgamation would duplicate json's internals). The two conditions of value() go through a trait in value.hpp, like the others. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Regenerate the amalgamated headers Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
12 KiB
nlohmann::basic_json::operator[]
// (1)
reference operator[](size_type idx);
const_reference operator[](size_type idx) const;
// (2)
reference operator[](typename object_t::key_type key);
const_reference operator[](const typename object_t::key_type& key) const;
// (3)
template<typename KeyType>
reference operator[](KeyType&& key);
template<typename KeyType>
const_reference operator[](KeyType&& key) const;
// (4)
reference operator[](const json_pointer& ptr);
const_reference operator[](const json_pointer& ptr) const;
- Returns a reference to the array element at specified location
idx. - Returns a reference to the object element with specified key
key. The non-const qualified overload takes the key by value. - See 2. This overload is only available if
KeyTypeis comparable with#!cpp typename object_t::key_typeand#!cpp typename object_comparator_t::is_transparentdenotes a type. - Returns a reference to the element with specified JSON pointer
ptr.
Template parameters
KeyType- A type for an object key other than
json_pointerthat is comparable withstring_tusingobject_comparator_t. This can also be a string view (C++17).
Iterator invalidation
For the non-const versions 1. and 4., when passing an array index that does not exist, it is created and filled with
a #!json null value before a reference to it is returned. For this, a reallocation can happen, in which case all
iterators (including the end() iterator) and all references to the elements are invalidated.
For ordered_json, also passing an object key to the non-const versions 2., 3., and 4., a
reallocation can happen which again invalidates all iterators and all references.
Parameters
idx(in)- index of the element to access
key(in)- object key of the element to access
ptr(in)- JSON pointer to the desired element
Return value
- (const) reference to the element at index
idx - (const) reference to the element at key
key - (const) reference to the element at key
key - (const) reference to the element pointed to by
ptr
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.305if the JSON value is not an array or null; in that case, using the[]operator with an index makes no sense. - Throws
#!cpp std::length_errorifidxequals the maximum value ofsize_type; the array is left unchanged. (This is the one index for which growing the array to hold it cannot be expressed as asize_typesize, the same way an oversizedresizethrows.)
- Throws
-
The function can throw the following exceptions:
- Throws
type_error.305if the JSON value is not an object or null; in that case, using the[]operator with a key makes no sense.
- Throws
-
See 2.
-
The function can throw the following exceptions:
- Throws
parse_error.106if an array index in the passed JSON pointerptrbegins with '0'. - Throws
parse_error.109if an array index in the passed JSON pointerptris not a number. - Throws
out_of_range.402if the array index '-' is used in the passed JSON pointerptrfor the const version. - Throws
out_of_range.404if the JSON pointerptrcan not be resolved. - Throws
out_of_range.410if an array index in the passed JSON pointerptrexceeds the range ofsize_type(e.g., on 32-bit platforms).
For the const version, an object key or array index in
ptrthat does not exist is not reported by an exception, but is undefined behavior (see the notes below). Useatfor checked access. - Throws
Complexity
- Constant if
idxis in the range of the array. Otherwise, linear inidx - size(). - Logarithmic in the size of the container.
- Logarithmic in the size of the container.
- Logarithmic in the size of the container.
Notes
!!! danger "Undefined behavior and runtime assertions"
The following cases apply to the **const** overloads; the non-const overloads instead insert the missing element
(see the notes below).
1. If the element at index `idx` does not exist, the behavior is undefined and is **guarded by a
[runtime assertion](../../features/assertions.md)**!
2. If the element with key `key` does not exist, the behavior is undefined and is **guarded by a
[runtime assertion](../../features/assertions.md)**!
3. If the JSON pointer `ptr` refers to an object key or an array index that does not exist, the behavior is
undefined and is **guarded by a [runtime assertion](../../features/assertions.md)**!
-
The non-const version may add values: If
idxis beyond the range of the array (i.e.,idx >= size()), then the array is silently filled up with#!json nullvalues to makeidxa valid reference to the last stored element. In case the value was#!json nullbefore, it is converted to an array. -
If
keyis not found in the object, then it is silently added to the object and filled with a#!json nullvalue to makekeya valid reference. In case the value was#!json nullbefore, it is converted to an object. -
See 2.
-
nullvalues are created in arrays and objects if necessary.In particular:
- If the JSON pointer points to an object key that does not exist, it is created and filled with a
#!json nullvalue before a reference to it is returned. - If the JSON pointer points to an array index that does not exist, it is created and filled with a
#!json nullvalue before a reference to it is returned. All indices between the current maximum and the given index are also filled with#!json null. - The special value
-is treated as a synonym for the index past the end.
!!! note "Creating intermediate levels that don't exist yet"
When the JSON pointer traverses intermediate levels that don't exist at all yet (not just a missing leaf), each missing level is created as an array or an object depending on whether the corresponding pointer token parses as a non-negative integer: a numeric token creates an array, a non-numeric token creates an object. For example, on an initially `#!json null` value, `/foo/0/0/0` creates nested arrays, while `/foo/one/one/one` creates nested objects. This is not specified by the JSON Pointer RFC; it is this library's own, intentional disambiguation rule. See also [JSON Pointer](../../features/json_pointer.md). - If the JSON pointer points to an object key that does not exist, it is created and filled with a
!!! warning "Deprecation"
Overload (4) also accepts a [`json_pointer`](../json_pointer/index.md) whose template argument is a `basic_json`
specialization (e.g., `nlohmann::json_pointer<nlohmann::json>`) instead of a string type. This is deprecated since
version 3.11.0 and will be removed in a future major version; use `basic_json::json_pointer` (for `json`,
`nlohmann::json_pointer<std::string>`) instead.
You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated
function.
See the [migration guide](../../integration/migration_guide.md#json-pointers) for how to update existing code.
Examples
??? example "Example: (1) access specified array element"
The example below shows how array elements can be read and written using `[]` operator. Note the addition of
`#!json null` values.
```cpp
--8<-- "examples/operator_array__size_type.cpp"
```
Output:
```json
--8<-- "examples/operator_array__size_type.output"
```
??? example "Example: (1) access specified array element (const)"
The example below shows how array elements can be read using the `[]` operator.
```cpp
--8<-- "examples/operator_array__size_type_const.cpp"
```
Output:
```json
--8<-- "examples/operator_array__size_type_const.output"
```
??? example "Example: (2) access specified object element"
The example below shows how object elements can be read and written using the `[]` operator.
```cpp
--8<-- "examples/operator_array__object_t_key_type.cpp"
```
Output:
```json
--8<-- "examples/operator_array__object_t_key_type.output"
```
??? example "Example: (2) access specified object element (const)"
The example below shows how object elements can be read using the `[]` operator.
```cpp
--8<-- "examples/operator_array__object_t_key_type_const.cpp"
```
Output:
```json
--8<-- "examples/operator_array__object_t_key_type_const.output"
```
??? example "Example: (3) access specified object element using string_view"
The example below shows how object elements can be read using the `[]` operator.
```cpp
--8<-- "examples/operator_array__keytype.c++17.cpp"
```
Output:
```json
--8<-- "examples/operator_array__keytype.c++17.output"
```
??? example "Example: (3) access specified object element using string_view (const)"
The example below shows how object elements can be read using the `[]` operator.
```cpp
--8<-- "examples/operator_array__keytype_const.c++17.cpp"
```
Output:
```json
--8<-- "examples/operator_array__keytype_const.c++17.output"
```
??? example "Example: (4) access specified element via JSON Pointer"
The example below shows how values can be read and written using JSON Pointers.
```cpp
--8<-- "examples/operator_array__json_pointer.cpp"
```
Output:
```json
--8<-- "examples/operator_array__json_pointer.output"
```
??? example "Example: (4) access specified element via JSON Pointer (const)"
The example below shows how values can be read using JSON Pointers.
```cpp
--8<-- "examples/operator_array__json_pointer_const.cpp"
```
Output:
```json
--8<-- "examples/operator_array__json_pointer_const.output"
```
See also
- documentation on unchecked access
- documentation on runtime assertions
- see
atfor access by reference with range checking - see
valuefor access with default value - basic_json_view::operator[] - the same access on a zero-copy view (a duplicate
key resolves to the first member, whereas
parse()keeps the last; a missing key gives a discarded view instead of undefined behavior)
Version history
- Added in version 1.0.0. Fixed in version 3.13.0 to throw
#!cpp std::length_errorinstead of emptying the array and accessing it out of bounds whenidxequals the maximum value ofsize_type. A missing index in the const version is guarded by a runtime assertion since version 3.13.0. - Added in version 1.0.0. Added overloads for
T* keyin version 1.1.0. Removed overloads forT* key(replaced by 3) in version 3.11.0. - Added in version 3.11.0. Fixed in version 3.13.0 to consistently accept
std::string_view-convertible keys, as already supported byat,value,find, and other lookup functions. - Added in version 2.0.0. A missing array index in the const version is guarded by a runtime assertion since
version 3.13.0. Throws
parse_error.109instead ofout_of_range.404for a one-character array index that is not a digit (e.g.,/x) in version 3.13.0, as it already did for longer ones.