Add std::format and fmt support (#5224)

*  add std::format and fmt support

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

* ♻️ reorganize PR

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

* 🧛 fix build

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

* 🧛 fix build

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

* 🧛 fix build

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

---------

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
This commit is contained in:
Niels Lohmann
2026-07-02 15:59:36 +02:00
committed by GitHub
parent ca49ab6123
commit 8d7e0046f4
21 changed files with 824 additions and 0 deletions
+25
View File
@@ -171,6 +171,31 @@ The library uses `std::numeric_limits<number_float_t>::digits10` (15 for IEEE `d
See [this section](../features/types/number_handling.md#number-serialization) on the library's number handling for more information.
### Using JSON values with `std::format` or `fmt`
!!! question
- Can I use `std::format("{}", j)` on a JSON value?
- Can I use `fmt::format("{}", j)` or `fmt::print("{}", j)` (the [{fmt}](https://github.com/fmtlib/fmt) library) on a JSON value?
`std::format` works out of the box since version 3.12.x, as long as the standard library provides
`<format>` (see [`JSON_HAS_STD_FORMAT`](../api/macros/json_has_std_format.md)); see
[`std::formatter<basic_json>`](../api/basic_json/std_formatter.md) for details, including the `#!cpp "{:#}"`
pretty-print spec, indent widths (`#!cpp "{:2}"`), and custom indent characters (`#!cpp "{:.>#}"`).
For `fmt`, the library ships [`format_as`](../api/basic_json/format_as.md), a small customization point
`fmt` looks for via argument-dependent lookup. It only has an effect on fmt 10.0.0 through 11.0.2 — from
fmt 11.1.0 onwards, `fmt` no longer picks up a `format_as` overload that returns a `std::string`. On such
versions (or any version, if you also want the same `#!cpp "{:#}"`/width/fill-and-align spec support that
`std::formatter<basic_json>` has), define your own `fmt::formatter` specialization; see
[`format_as`](../api/basic_json/format_as.md) for a recipe that mirrors it.
If you get ambiguous-overload errors when passing a JSON value to `fmt::format`/`fmt::print` without any
`fmt::formatter<json>` specialization in scope, that's `fmt` picking up `basic_json`'s implicit
`operator ValueType()` conversion operator (see [#964](https://github.com/nlohmann/json/issues/964) and
[#958](https://github.com/nlohmann/json/issues/958)); disabling it via
[`JSON_USE_IMPLICIT_CONVERSIONS 0`](../api/macros/json_use_implicit_conversions.md) avoids the ambiguity.
## Compilation issues
### Android SDK