Files
json/docs/mkdocs/docs/api/basic_json_view/count.md
T
Niels Lohmann 5c0e929b41 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-13 22:22:23 +02:00

2.1 KiB

nlohmann::basic_json_view::count

size_type count(string_view_t key) const;
size_type count(const char* key) const;
size_type count(const string_t& key) const;

Returns #!cpp 1 if the value is an object with a member with key key, #!cpp 0 otherwise.

Parameters

key (in)
key value of the element to count

Return value

#!cpp 1 if the value is an object and has a member with key key, #!cpp 0 otherwise.

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

This method always returns #!cpp 0 when the value is not an object -- including a discarded view.

Unlike BasicJsonType::count(), whose return value can in principle exceed #!cpp 1 for an ObjectType that allows multiple entries per key, count() here never does: it is exactly contains() as #!cpp 0/#!cpp 1. This holds even if the source text has a duplicate key -- see the Notes on duplicate keys of operator[] -- because a #!cpp count() > 1 result would require counting every member with a matching key (the lookup functions resolve to the last one).

Examples

??? example

The example below validates that every transaction of a batch carries a mandatory `amount` field, using
`count()` before deciding whether to materialize a transaction at all.

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

Output:

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

See also

Version history

  • Added in version 3.13.0.