* docs: new design for the documentation site Apply the brand to the Material for MkDocs site: Inter and JetBrains Mono served by the site (upright and real italic), brand colours, blue header band with the syntax pattern, wordmark in the header, new home page (hero, cards, animated feature tour), 404 page, polish for tabs, search, footer, focus rings, tables and code blocks, and theme features (code copy, previous/next footer, TOC follow, search suggestions). Draw the number railroad diagram, the parser callback events and the iterator illustrations as inline SVGs that follow the light and dark scheme. The generator scripts are in docs/mkdocs/scripts/figures; the feature slideshow (json-light.svg, json-dark.svg, replacing json.gif on the home page) is built by docs/mkdocs/scripts/slideshow. Decision nodes in five flowcharts become hexagons, which need far less room. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: add figures, table captions and a macro chooser - Figures with numbered captions: SAX stepper, json_view layout and edit stepper, exception map, JSON pointer and patch walkers, QA pipeline, scaling and binary size charts, roadmap lanes, release timeline, integration decision tree and namespace builder - Table captions (nj-table-caption) on 9 pages - Compile times: modules and PCH charts, filesystem section, re-measured Figure 1, links between features/modules.md and compile_times.md - Interactive macro chooser for features/arbitrary_types.md - Link check: exclude URLs that answer the plugin with 400/401/419 or are dead (customers.md) Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: macro chooser generates adl_serializer for non-default-constructible types Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: cross-link concept pages and API pages in See also sections Add See also links in both directions between the concept pages (features, home, integration) and the API pages, write API links in code font, give every entry a comment after a dash, and show the callback event figure on the parser callbacks page. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: address review comments on the new design - Home: add a "Latest release" button - Sponsors: update the list and group it by tier - Features: list all feature pages on the index page - Releases: add highlights per release, link the 4.0 roadmap, add the first commit to the timeline - Exceptions: prefix all example messages with the exception name - API: no code font for format names in the See also links of the to_/from_ pages - Merge Patch: show the document before, the patch, and the result - Replace "--" with typographic dashes, mark external links with an icon, center Mermaid diagrams Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
5.5 KiB
Iterators
Overview
A basic_json value is a container and allows access via iterators. Depending on the value type, basic_json stores zero or more values.
As for other containers, begin() returns an iterator to the first value and
end() returns an iterator to the value following the last value. The latter iterator is a
placeholder and cannot be dereferenced. In case of null values, empty arrays, or empty objects, begin() will return
end().
The range of `begin()` and `end()`: `begin()` refers to the first element, `end()` to the position after the last element, which must not be dereferenced.
Iteration order for objects
When iterating over objects, values are ordered with respect to the object_comparator_t type which defaults to std::less. See the types documentation for more information.
??? example "Example: iteration order of object values"
```cpp
// create JSON object {"one": 1, "two": 2, "three": 3}
json j;
j["one"] = 1;
j["two"] = 2;
j["three"] = 3;
for (auto it = j.begin(); it != j.end(); ++it)
{
std::cout << *it << std::endl;
}
```
Output:
```json
1
3
2
```
The reason for the order is the lexicographic ordering of the object keys "one", "three", "two".
Access object keys during iteration
The JSON iterators have two member functions, key() and value() to access the object key and stored value, respectively. When calling key() on a non-object iterator, an invalid_iterator.207 exception is thrown.
??? example "Example: access object keys with key() and value()"
```cpp
// create JSON object {"one": 1, "two": 2, "three": 3}
json j;
j["one"] = 1;
j["two"] = 2;
j["three"] = 3;
for (auto it = j.begin(); it != j.end(); ++it)
{
std::cout << it.key() << " : " << it.value() << std::endl;
}
```
Output:
```json
one : 1
three : 3
two : 2
```
Range-based for loops
C++11 allows using range-based for loops to iterate over a container.
for (auto it : j_object)
{
// "it" is of type json::reference and has no key() member
std::cout << "value: " << it << '\n';
}
For this reason, the items() function allows accessing iterator::key() and
iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there
is no access to the underlying iterator.
for (auto& el : j_object.items())
{
std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
}
The items() function also allows using structured bindings (C++17):
for (auto& [key, val] : j_object.items())
{
std::cout << "key: " << key << ", value:" << val << '\n';
}
!!! note
When iterating over an array, `key()` will return the index of the element as string. For primitive types (e.g., numbers), `key()` returns an empty string.
!!! warning
Using `items()` on temporary objects is dangerous. Make sure the object's lifetime exceeds the iteration. See [#2040](https://github.com/nlohmann/json/issues/2040) for more information.
Reverse iteration order
rbegin() and rend() return iterators in the reverse
sequence.
The range of `rbegin()` and `rend()` over the same elements: `rbegin()` refers to the last element and `rend()` to the position before the first one. Each reverse iterator stores an iterator to the element after the one it refers to.
??? example "Example: reverse iteration with rbegin() and rend()"
```cpp
json j = {1, 2, 3, 4};
for (auto it = j.rbegin(); it != j.rend(); ++it)
{
std::cout << *it << std::endl;
}
```
Output:
```json
4
3
2
1
```
Iterating strings and binary values
Note that "value" means a JSON value in this setting, not values stored in the underlying containers. That is, *begin() returns the complete string or binary array and is also safe if the underlying string or binary array is empty.
??? example "Example: iterate over a string value"
```cpp
json j = "Hello, world";
for (auto it = j.begin(); it != j.end(); ++it)
{
std::cout << *it << std::endl;
}
```
Output:
```json
"Hello, world"
```
Iterator invalidation
| Operations | invalidated iterators |
|---|---|
clear |
all |
See also
begin- /end- iterators to the first and one past the last elementrbegin- /rend- reverse iteratorscbegin- /cend- const iteratorsitems- iterate over keys and values- Object Order - iteration order of object keys
- Element Access - access single elements
- Modifying values - add and remove elements (including iterator invalidation rules)