1 # <small>nlohmann::basic_json::</small>items
4 iteration_proxy<iterator> items() noexcept;
5 iteration_proxy<const_iterator> items() const noexcept;
8 This function allows accessing `iterator::key()` and `iterator::value()` during range-based for loops. In these loops, a
9 reference to the JSON values is returned, so there is no access to the underlying iterator.
11 For loop without `items()` function:
14 for (auto it = j_object.begin(); it != j_object.end(); ++it)
16 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
20 Range-based for loop without `items()` function:
23 for (auto it : j_object)
25 // "it" is of type json::reference and has no key() member
26 std::cout << "value: " << it << '\n';
30 Range-based for loop with `items()` function:
33 for (auto& el : j_object.items())
35 std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
39 The `items()` function also allows using
40 [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding) (C++17):
43 for (auto& [key, val] : j_object.items())
45 std::cout << "key: " << key << ", value:" << val << '\n';
51 iteration proxy object wrapping the current value with an interface to use in range-based for loops
55 Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
63 When 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.
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.
75 The following code shows an example for `items()`.
78 --8<-- "examples/items.cpp"
84 --8<-- "examples/items.output"
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.
93 !!! warning "Deprecation"
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()`.
99 You should be warned by your compiler with a `-Wdeprecated-declarations` warning if you are using a deprecated