Files
json/docs/mkdocs/docs/api/basic_json_view/find.md
T
Niels Lohmann 08dcdaf9b8 Document element access, lookup, and iteration of json_view
- API pages for operator[], at, front, back, find, contains, count,
  begin, end, cbegin, cend, items, and type_name of basic_json_view,
  linked both ways with the basic_json pages
- the feature page and size() describe document order and duplicate
  keys
- the examples show when the view helps: reading a few fields of a large
  text, probing optional members, and members in source order

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-09-30 21:01:33 +02:00

2.0 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.

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.