Files
json/docs/mkdocs/docs/api/basic_json_view/find.md
Niels Lohmann c05764cbda Index the large objects of json_view
Lookups in objects are linear, as for ordered_json. Objects with 128
members or more now get a hash table after parsing (open addressing; the
first of duplicate keys is kept, as for the linear search), so that
operator[], at(), find(), contains(), count(), value(), and JSON pointers
take constant time on average in them; the idea of switching to a hash
table for large objects is Boost.JSON's. The parser notes such objects when
it closes them (out of line, so that the parse loop only has a call for
it), and the object node keeps the number of its table.

Looking up each key of an object with 10,000 members: 59.8 ms -> 0.16 ms.
Parsing (json_document::parse, best of 7, separate processes): most files
within 1%; canada +5%, mesh.pretty +3%, citm +3%.

Tests: objects with 127, 128, 129, and 10,000 members (escaped, empty,
and duplicate keys, missing keys, comparisons), nested large objects, and
documents reused with read().

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-09-30 15:08:48 +02:00

2.1 KiB

nlohmann::basic_json_view::find

iterator find(string_view_t key) const;
iterator find(const char* key) const;
iterator find(const string_t& key) const;

Finds a member with key key -- the first one, should the key occur more than once (see Notes on duplicate keys). If the value is not an object, or no member has this key, end() is returned.

Parameters

key (in)
key value of the element to search for

Return value

An iterator to the member with key key, or end() if there is none or the value is not an object.

Exception safety

No-throw guarantee: this function never throws exceptions.

Complexity

Linear in the number of members: as for ordered_json, members are compared one after another, in document order, stopping at the first match. Each comparison first checks the key's length -- already known from the index, without reading the key bytes -- before comparing its content. Objects with 128 or more members get a hash index while parsing, so that a lookup in them takes constant time on average.

Notes

Unlike BasicJsonType::find, which always returns #!cpp end() for a non-object type, this also does so for a discarded view -- there is no separate "invalid" iterator to return.

Examples

??? example

The example below scans a batch of events for those that carry an optional `user_id` field, using `find()`
instead of [`operator[]`](operator[].md) (which would throw for the events that are not objects at all) or
[`contains()`](contains.md) followed by a second lookup. Events without a match are never materialized.

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

Output:

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

See also

Version history

  • Added in version 3.13.0.