Looking up the last member of a duplicate key cannot stop at a match, so every lookup scanned the whole object (1.6 to 3.4 times slower for small objects). operator[](key), at, find, value, contains, count, and JSON pointer resolution return the first member again, as yyjson and simdjson do; materialize() and get<map>() keep the last value, as parse(). The documentation says so in the feature page and on each lookup page, and explains how to get the value parse() would give. The integer index templates and the discarded chaining of operator[] stay. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2.5 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
!!! warning "Duplicate keys: the first member wins"
If the source text repeats a key, this resolves to the *first* member with it, not to the last one that
[`materialize()`](materialize.md) and `parse()` keep. See the [Notes on duplicate keys](operator[].md#notes) of
`operator[]` and [Duplicate keys](../../features/json_view.md#duplicate-keys) for the reasons and for how to get
the last value.
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 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
- find - find a value in an object
- contains - checks whether a key exists
BasicJsonType::count- the corresponding function ofbasic_json
Version history
- Added in version 3.13.0.