• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# <small>nlohmann::basic_json::</small>items
2
3```cpp
4iteration_proxy<iterator> items() noexcept;
5iteration_proxy<const_iterator> items() const noexcept;
6```
7
8This function allows accessing `iterator::key()` and `iterator::value()` during range-based for loops. In these loops, a
9reference to the JSON values is returned, so there is no access to the underlying iterator.
10
11For loop without `items()` function:
12
13```cpp
14for (auto it = j_object.begin(); it != j_object.end(); ++it)
15{
16    std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
17}
18```
19
20Range-based for loop without `items()` function:
21
22```cpp
23for (auto it : j_object)
24{
25    // "it" is of type json::reference and has no key() member
26    std::cout << "value: " << it << '\n';
27}
28```
29
30Range-based for loop with `items()` function:
31
32```cpp
33for (auto& el : j_object.items())
34{
35    std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
36}
37```
38
39The `items()` function also allows using
40[structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding) (C++17):
41
42```cpp
43for (auto& [key, val] : j_object.items())
44{
45    std::cout << "key: " << key << ", value:" << val << '\n';
46}
47```
48
49## Return value
50
51iteration proxy object wrapping the current value with an interface to use in range-based for loops
52
53## Exception safety
54
55Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
56
57## Complexity
58
59Constant.
60
61## Notes
62
63When iterating over an array, `key()` will return the index of the element as string (see example). For primitive types
64(e.g., numbers), `key()` returns an empty string.
65
66!!! danger "Lifetime issues"
67
68    Using `items()` on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See
69    <https://github.com/nlohmann/json/issues/2040> for more information.
70
71## Examples
72
73??? example
74
75    The following code shows an example for `items()`.
76
77    ```cpp
78    --8<-- "examples/items.cpp"
79    ```
80
81    Output:
82
83    ```json
84    --8<-- "examples/items.output"
85    ```
86
87## Version history
88
89- Added `iterator_wrapper` in version 3.0.0.
90- Added `items` and deprecated `iterator_wrapper` in version 3.1.0.
91- Added structured binding support in version 3.5.0.
92
93!!! warning "Deprecation"
94
95    This function replaces the static function `iterator_wrapper` which was introduced in version 1.0.0, but has been
96    deprecated in version 3.1.0. Function `iterator_wrapper` will be removed in version 4.0.0. Please replace all
97    occurrences of `#!cpp iterator_wrapper(j)` with `#!cpp j.items()`.
98
99    You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated
100    function.
101