Files
json/docs/mkdocs/docs/api/basic_json_view/find.md
T
Niels Lohmann c7df23666f 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>
2026-10-09 16:11: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 last 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, scanning all of them, since the last match is wanted. 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.