Files
json/docs/mkdocs/docs/api/basic_json/clear.md
T
Niels Lohmann fc4c9c3446 Fix clear() to also reset the subtype of a binary value (#5680)
* Fix clear() to also reset the subtype of a binary value

clear() on a binary value cleared the bytes but left the subtype
untouched, so the result was not equal to a default-constructed
binary value even though the documentation says clear() has the same
effect as *this = basic_json(type()). The fix calls
byte_container_with_subtype::clear_subtype() alongside the existing
clear() call.

Extended the "filled binary" clear() test in unit-modifiers.cpp with
a case that uses a subtype, since the existing cases only covered
binary values without one.

Fixes #5669.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* Fix the table alignment in clear.md

Addresses review comment by @gregmarr.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

---------

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-09-30 20:06:51 +02:00

1.5 KiB

nlohmann::basic_json::clear

void clear() noexcept;

Clears the content of a JSON value and resets it to the default value as if basic_json(value_t) would have been called with the current value type from type():

Value type initial value
null null
boolean false
string ""
number 0
binary An empty byte vector with no subtype
object {}
array []

Has the same effect as calling

*this = basic_json(type());

Exception safety

No-throw guarantee: this function never throws exceptions.

Complexity

Linear in the size of the JSON value.

Notes

All iterators, pointers, and references related to this container are invalidated.

Examples

??? example

The example below shows the effect of `clear()` to different
JSON types.

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

Output:

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

Version history

  • Added in version 1.0.0.
  • Added support for binary types in version 3.8.0.
  • Fixed in version 3.13.0 to also clear the subtype of a binary value; before, the subtype was left unchanged.