From gregmarr's review of #5622: - count() counts every member with the key, so count(key) > 1 detects duplicate keys; it was contains() as 0/1 before. - get_to() passes types that get<T>() does not convert directly to from_json with the existing value, as basic_json::get_to() does, so that a from_json which sets only the fields present keeps the others. - array_index() checks the empty token and "-" first; the results are unchanged. - Docs: no "if an exception is thrown" where a view never changes anything; the borrowed source must also stay unmodified; items() on a temporary view is safe; back()/front() notes shortened; the basic_json see-also entries say how the view's results can differ. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2.3 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 the number of members with key key if the value is an object, #!cpp 0 otherwise. Members with a repeated
key are all counted.
Parameters
key(in)- key value of the element to count
Return value
the number of members of the object with key key (duplicates included), or #!cpp 0 if the value is not an object
or has no such member.
Exception safety
No-throw guarantee: this function never throws exceptions.
Complexity
Linear in the number of members: unlike the lookup functions, count() does not stop at the first match, because it
has to count every member with the key. Members are compared one after another, in document order. 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.
If the source text repeats a key, count() returns more than #!cpp 1 for it, even though the
materialized value (like the result of parse()) would have only one member with that key. Hence
#!cpp count(key) > 1 detects duplicate keys. This is unlike the lookup functions
(operator[], at, find, contains), which resolve to the
first member; see the Notes on duplicate keys of operator[].
Examples
??? example
The example below validates that every transaction of a batch carries exactly one `amount` field, using
`count()` before deciding whether to materialize a transaction at all. It reports a transaction with no `amount`
field and one with a duplicated `amount` field.
```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.