Files
json/docs/mkdocs/docs/api/basic_json_view/front.md
T
Niels Lohmann 7b755737b4 Address the review of json_view element access
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>
2026-10-18 10:05:51 +02:00

1.8 KiB

nlohmann::basic_json_view::front

basic_json_view front() const;

Returns the first element of an array, the first member value of an object, or the value itself if it is primitive (as for BasicJsonType::front(), a primitive value is a range of one element).

Return value

The first element or member value. For a primitive value (number, string, boolean), the value itself.

Exception safety

Strong guarantee: there are no changes to the view or the document it refers to.

Exceptions

Throws invalid_iterator.214 if the view is null or discarded, or if it is an empty array or object.

This exception does not carry a JSON_DIAGNOSTICS path: the view has no BasicJsonType value to point at, so the exception is created without one, even if BasicJsonType was built with JSON_DIAGNOSTICS enabled.

Complexity

Constant.

Notes

Unlike BasicJsonType::front(), which has undefined behavior for an empty array or object, front() throws invalid_iterator.214 for an empty array, an empty object, a null value, or a discarded view.

Examples

??? example

The example below reads only the earliest entry of a build log with `front()`, without materializing the rest
of the (possibly long) log.

```cpp
--8<-- "examples/basic_json_view__front.cpp"
```

Output:

```json
--8<-- "examples/basic_json_view__front.output"
```

See also

Version history

  • Added in version 3.13.0.