• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# <small>nlohmann::basic_json::</small>count
2
3```cpp
4// (1)
5size_type count(const typename object_t::key_type& key) const;
6
7// (2)
8template<typename KeyType>
9size_type count(KeyType&& key) const;
10```
11
121. Returns the number of elements with key `key`. If `ObjectType` is the default `std::map` type, the return value will
13   always be `0` (`key` was not found) or `1` (`key` was found).
142. See 1. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and
15   `#!cpp typename object_comparator_t::is_transparent` denotes a type.
16
17## Template parameters
18
19`KeyType`
20:   A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with
21    [`string_t`](string_t.md) using  [`object_comparator_t`](object_comparator_t.md).
22    This can also be a string view (C++17).
23
24## Parameters
25
26`key` (in)
27:   key value of the element to count.
28
29## Return value
30
31Number of elements with key `key`. If the JSON value is not an object, the return value will be `0`.
32
33## Exception safety
34
35Strong exception safety: if an exception occurs, the original value stays intact.
36
37## Complexity
38
39Logarithmic in the size of the JSON object.
40
41## Notes
42
43This method always returns `0` when executed on a JSON type that is not an object.
44
45## Examples
46
47??? example "Example: (1) count number of elements"
48
49    The example shows how `count()` is used.
50
51    ```cpp
52    --8<-- "examples/count__object_t_key_type.cpp"
53    ```
54
55    Output:
56
57    ```json
58    --8<-- "examples/count__object_t_key_type.output"
59    ```
60
61??? example "Example: (2) count number of elements using string_view"
62
63    The example shows how `count()` is used.
64
65    ```cpp
66    --8<-- "examples/count__keytype.c++17.cpp"
67    ```
68
69    Output:
70
71    ```json
72    --8<-- "examples/count__keytype.c++17.output"
73    ```
74
75## Version history
76
771. Added in version 3.11.0.
782. Added in version 1.0.0. Changed parameter `key` type to `KeyType&&` in version 3.11.0.
79