Files
json/docs/mkdocs/docs/api/basic_json_view/count.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.2 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. Objects with 128 or more members get a hash index while parsing, so that a lookup in them takes constant time on average.

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.