* Review and extend the documentation, and check it in CI A review of all documentation pages found factual errors, dead links, missing cross-references, and gaps in examples. This fixes them and adds checks so the same problems are caught automatically. Fixes: - wrong signatures and version histories (operator!= C++20 member, binary() subtype type, get<PointerType>(), JSON_NO_THREAD_LOCAL, ...) - stale descriptions (number parsing since #5283, UBJSON table, SAX example that no longer compiled, tsl::ordered_map advice) - dead internal and external links; repology.org badges (the domain is suspended) replaced by badges that query the registries directly - deprecation notes link the migration guide; the guide itself fixed Additions: - "See also" sections, cross-references, 25 runnable examples, 12 Mermaid diagrams, new API pages for json_pointer::operator<=> and byte_container_with_subtype::operator==/!= - landing page, guides for untrusted input and performance - "unreleased" badge after versions newer than the latest release Checks: - strict documentation build (broken links/anchors fail it); CI and the publish workflow fetch the full history the build needs - weekly external link check, Mermaid syntax check in CI - check_structure.py: example titles, heading levels, alt texts, header links, docset index coverage; its unused-example check works again - all examples produce the same output on every platform Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Keep the customer links that could not be fixed A dead link on the customers page is still the evidence of where the use of the library was documented. Keep the original URLs of the entries without a working replacement (Marne, Cisco Webex Desk Camera, Philips Hue, CyberArk) and exclude exactly these URLs from the link check. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Correct the duplicate-key recipe's claim about SAX positions The SAX interface's key() receives no position either; only parse_error() does. Also note that the recipe does not report the path to the repeated key (see discussion #5085). Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Say the library is available as a single header and mention json_fwd.hpp Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Correct documentation errors found while hunting for bugs - patch/patch_inplace: list the JSON pointer errors parse_error.106-109 and out_of_range.402/404, and quote the actual parse_error.105 message. - unflatten: list parse_error.106/107/108 and out_of_range.404. - to_bson: list out_of_range.415 (binary subtype above 255) and note that 412 and 415 are new in 3.13.0. - to_string: state that string_t must be convertible to std::string, also in the StringType requirements table. - JSON Lines: a `while (input >> j)` loop also throws after the last value for concatenated JSON values; show a loop that works for both. - BON8: a string gets 0xFF only if nothing follows it in the message; a string at the end of an array or object is ended by 0xFE. - custom_string_type.hpp: add operator+=(char), which the "Always required" list asks for (json_pointer::to_string, flatten, unflatten, and diff did not compile), and an ADL int_to_string for diff and items. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Cache the release headers with functools.lru_cache Codacy (Pylint) flagged the mutable default argument that header() used as its cache. functools.lru_cache keeps the same memoization without it. The script's output is unchanged. Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
5.4 KiB
Serialization
Serialization is the process of turning a JSON value back into JSON text. It is the counterpart to
parsing. The central function is dump, which returns the JSON text as
a string.
json j = {{"pi", 3.141}, {"happy", true}};
std::string s = j.dump(); // {"happy":true,"pi":3.141}
To write a value directly to a stream (for example, a file or #!cpp std::cout), the
operator<< is provided:
std::cout << j << std::endl;
!!! note "String, not raw value"
`dump` always returns a **JSON text**. Serializing a JSON string therefore includes the surrounding quotes and
escapes special characters. To obtain the *contained* string value without quotes, use
[`get<std::string>()`](conversions.md) instead of `dump`. See the [converting values](conversions.md) page.
Pretty-printing
By default, dump produces the most compact representation without any superfluous whitespace. Passing a non-negative
indent argument pretty-prints the output with the given number of spaces per level:
??? example "Example: pretty-print JSON values with dump()"
```cpp
--8<-- "examples/dump.cpp"
```
Output:
```json
--8<-- "examples/dump.output"
```
The indentation character can be changed with the second argument (e.g., a tab #!cpp '\t'). An indent of 0 inserts
newlines but no leading spaces, and the default of #!cpp -1 selects the compact single-line form.
Non-ASCII characters
Strings are stored and serialized as UTF-8 (see types). By default, dump copies valid
non-ASCII characters as-is. Setting the third argument ensure_ascii to #!cpp true escapes all non-ASCII characters
with \uXXXX sequences, so that the output contains only ASCII characters:
json j = "苹果";
j.dump(); // "苹果"
j.dump(-1, ' ', true); // "苹果"
Handling invalid UTF-8
If a string contains invalid UTF-8 sequences (for example, because it holds data in another encoding such as Latin-1),
serialization fails by default. The fourth argument of dump selects an
error_handler:
strict(default) — throw atype_error.316exception.replace— replace invalid bytes with the Unicode replacement character U+FFFD (�).ignore— silently drop invalid bytes.
??? example "Example: serialize invalid UTF-8 with different error handlers"
```cpp
--8<-- "examples/error_handler_t.cpp"
```
Output:
```json
--8<-- "examples/error_handler_t.output"
```
!!! tip "Avoiding invalid UTF-8"
The best fix is to ensure that all strings are UTF-8 encoded before storing them. See the
[FAQ on non-ASCII characters](../home/faq.md#parse-errors-reading-non-ascii-characters) for how to convert wide or
Latin-1 strings.
Numbers, NaN, and binary values
- Numbers are serialized with enough precision to round-trip; see number serialization.
- NaN and infinity cannot be represented in JSON and are serialized as
#!json null; see NaN handling. The binary formats can preserve them. - Binary values have no JSON representation and are serialized as a helper object for debugging only; see binary values.
Using std::format, std::print, and fmt
Since version 3.12.0, JSON values can be formatted directly with C++20's
std::format whenever the standard library provides the
<format> header (controlled by JSON_HAS_STD_FORMAT). This is enabled by the
std::formatter<basic_json> specialization, which also makes JSON values work with
std::format_to and with C++23's std::print/std::println:
std::print("{}", j); // compact, like j.dump()
std::print("{:2}", j); // pretty-printed with indent 2 (like j.dump(2))
std::println("{:#}", j); // pretty-printed with the default indent
The format spec mirrors the dump parameters: #!cpp "{:#}" pretty-prints, a width such as #!cpp "{:2}" sets the
indent, and a fill-and-align prefix such as #!cpp "{:.>#}" sets the indent character.
For the {fmt} library, the library ships a
format_as helper. Note its behavior depends on the fmt version; see the
FAQ entry for the details and a recipe for a full
fmt::formatter specialization.
Serializing to other formats
Besides JSON text, a value can also be serialized to the more compact binary formats (BJData, BON8, BSON, CBOR, MessagePack, UBJSON).
See also
dump- serialize to a JSON-formatted stringoperator<<- serialize to a streamto_string- user-defined-conversion helperstd::formatter<basic_json>- use JSON values withstd::formatandstd::printformat_as- use JSON values with the {fmt} library- Parsing - the reverse operation