Files
json/docs/mkdocs/docs/api/basic_json_view/count.md
Niels Lohmann 5a9f59a688 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-29 14:02:50 +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, 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

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, not just finding the first 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.