mirror of
https://github.com/nlohmann/json.git
synced 2026-07-09 12:05:10 +00:00
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:
@@ -0,0 +1,94 @@
|
||||
# format_as(basic_json)
|
||||
|
||||
```cpp
|
||||
template <typename BasicJsonType>
|
||||
std::string format_as(const BasicJsonType& j);
|
||||
```
|
||||
|
||||
This function implements the [`format_as`](https://fmt.dev/latest/api/#formatting-user-defined-types)
|
||||
customization point used by the [{fmt}](https://github.com/fmtlib/fmt) library (fmtlib). It has no
|
||||
dependency on any `fmt` header and no effect at all unless a caller's translation unit also includes
|
||||
`fmt` and calls `fmt::format`/`fmt::print` on a JSON value.
|
||||
|
||||
## Template parameters
|
||||
|
||||
`BasicJsonType`
|
||||
: a specialization of [`basic_json`](index.md)
|
||||
|
||||
## Return value
|
||||
|
||||
string containing the serialization of the JSON value (same as [`dump()`](dump.md))
|
||||
|
||||
## Exception safety
|
||||
|
||||
Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
|
||||
|
||||
## Exceptions
|
||||
|
||||
Throws [`type_error.316`](../../home/exceptions.md#jsonexceptiontype_error316) if a string stored inside the JSON value
|
||||
is not UTF-8 encoded
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear.
|
||||
|
||||
## Possible implementation
|
||||
|
||||
```cpp
|
||||
template <typename BasicJsonType>
|
||||
std::string format_as(const BasicJsonType& j)
|
||||
{
|
||||
return j.dump();
|
||||
}
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
!!! warning "Version-dependent effect on fmt"
|
||||
|
||||
`fmt` only picks up a `format_as` overload that returns a `std::string` in fmt **10.0.0 through
|
||||
11.0.2**. Starting with fmt **11.1.0**, `fmt` restricts automatic `format_as` pickup to overloads that
|
||||
return an arithmetic type, so this function has no effect there (it is simply unused, not a compile
|
||||
error).
|
||||
|
||||
If you use fmt \>= 11.1.0, or want the same pretty-print spec support that
|
||||
[`std::formatter<basic_json>`](std_formatter.md) has (`#!cpp "{:#}"`, a width to set the indent such
|
||||
as `#!cpp "{:2}"`/`#!cpp "{:#2}"`, and fill-and-align to pick the indent character such as
|
||||
`#!cpp "{:.>#}"`), define your own `fmt::formatter` specialization mirroring the same logic:
|
||||
|
||||
```cpp
|
||||
--8<-- "../../../tests/fmt_formatter/project/main.cpp:formatter_recipe"
|
||||
```
|
||||
|
||||
This recipe isn't shipped by the library itself, since doing so would make `fmt` a build dependency
|
||||
(see the FAQ entry on
|
||||
[using JSON values with `std::format` or `fmt`](../../home/faq.md#using-json-values-with-stdformat-or-fmt)
|
||||
for more background) — but it *is* compiled and exercised against a real, current `fmt` release as
|
||||
part of the library's own test suite (`tests/fmt_formatter`, via CMake `FetchContent`), so it's kept in
|
||||
sync with `std::formatter<basic_json>` and verified to actually work, not just illustrative.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows how the library's `format_as()` function integrates with `fmt::format`,
|
||||
allowing argument-dependent lookup.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/format_as.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/format_as.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [dump](dump.md)
|
||||
- [std::formatter<basic_json>](std_formatter.md) - the `std::format` (C++20) equivalent
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.12.x.
|
||||
@@ -301,6 +301,7 @@ Access to the JSON value
|
||||
- [**operator<<(std::ostream&)**](../operator_ltlt.md) - serialize to stream
|
||||
- [**operator>>(std::istream&)**](../operator_gtgt.md) - deserialize from stream
|
||||
- [**to_string**](to_string.md) - user-defined `to_string` function for JSON values
|
||||
- [**format_as**](format_as.md) - user-defined `format_as` function for JSON values (fmt support)
|
||||
|
||||
## Literals
|
||||
|
||||
@@ -308,6 +309,7 @@ Access to the JSON value
|
||||
|
||||
## Helper classes
|
||||
|
||||
- [**std::formatter<basic_json>**](std_formatter.md) - make JSON values formattable with `std::format`
|
||||
- [**std::hash<basic_json>**](std_hash.md) - return a hash value for a JSON object
|
||||
- [**std::swap<basic_json>**](std_swap.md) - exchanges the values of two JSON objects
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# <small>std::</small>formatter<nlohmann::basic_json\>
|
||||
|
||||
```cpp
|
||||
namespace std {
|
||||
template <>
|
||||
struct formatter<nlohmann::basic_json, char>;
|
||||
}
|
||||
```
|
||||
|
||||
Specialization to make JSON values formattable with [`std::format`](https://en.cppreference.com/w/cpp/utility/format/format)
|
||||
(and the other members of C++20's `<format>` header, such as `std::format_to`).
|
||||
|
||||
A subset of the [standard format spec grammar](https://en.cppreference.com/w/cpp/utility/format/spec) is
|
||||
supported, repurposed for JSON pretty-printing; any other spec component (sign, the `0` flag, precision,
|
||||
`L`, a dynamic width such as `#!cpp "{:{}}"`, or a trailing type character) throws
|
||||
[`std::format_error`](https://en.cppreference.com/w/cpp/utility/format/format_error):
|
||||
|
||||
- `#!cpp "{}"` serializes the value the same way as [`dump()`](dump.md) (compact, no whitespace).
|
||||
- `#!cpp "{:#}"` ("alternate form") serializes the value the same way as `#!cpp dump(4)` (pretty-printed
|
||||
with an indent of 4).
|
||||
- A width, with or without `#!cpp "#"` (e.g. `#!cpp "{:2}"` or `#!cpp "{:#2}"`), serializes the value the
|
||||
same way as `#!cpp dump(width)` — a width on its own implies pretty-printing, since an indent size has
|
||||
no meaning for compact output.
|
||||
- `fill-and-align` (e.g. `#!cpp "{:.>#}"` or `#!cpp "{:.>3}"`) picks a custom indent character, the same
|
||||
way as `#!cpp dump(indent, indent_char)`. The alignment direction itself (`#!cpp '<'`, `#!cpp '>'`,
|
||||
`#!cpp '^'`) has no separate meaning for JSON values — only the fill character before it is used, and
|
||||
any of the three directions is accepted.
|
||||
|
||||
This specialization is only available for `#!cpp char`-based JSON values and only if the standard library
|
||||
provides `<format>`, controlled by the [`JSON_HAS_STD_FORMAT`](../macros/json_has_std_format.md) macro.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The example shows how to format JSON values with `std::format`.
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/std_formatter.c++20.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/std_formatter.c++20.output"
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
- [dump](dump.md) - serialization
|
||||
- [operator<<(std::ostream&)](../operator_ltlt.md) - serialize to stream
|
||||
- [format_as](format_as.md) - customization point used by `fmt::format` (fmtlib)
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.12.x.
|
||||
@@ -19,6 +19,7 @@ header. See also the [macro overview page](../../features/macros.md).
|
||||
- [**JSON_HAS_CPP_11**<br>**JSON_HAS_CPP_14**<br>**JSON_HAS_CPP_17**<br>**JSON_HAS_CPP_20**](json_has_cpp_11.md) - set supported C++ standard
|
||||
- [**JSON_HAS_FILESYSTEM**<br>**JSON_HAS_EXPERIMENTAL_FILESYSTEM**](json_has_filesystem.md) - control `std::filesystem` support
|
||||
- [**JSON_HAS_RANGES**](json_has_ranges.md) - control `std::ranges` support
|
||||
- [**JSON_HAS_STD_FORMAT**](json_has_std_format.md) - control `std::format`/`std::formatter` support
|
||||
- [**JSON_HAS_THREE_WAY_COMPARISON**](json_has_three_way_comparison.md) - control 3-way comparison support
|
||||
- [**JSON_NO_IO**](json_no_io.md) - switch off functions relying on certain C++ I/O headers
|
||||
- [**JSON_SKIP_UNSUPPORTED_COMPILER_CHECK**](json_skip_unsupported_compiler_check.md) - do not warn about unsupported compilers
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# JSON_HAS_STD_FORMAT
|
||||
|
||||
```cpp
|
||||
#define JSON_HAS_STD_FORMAT /* value */
|
||||
```
|
||||
|
||||
This macro indicates whether the standard library has support for `std::format`/`std::formatter` (that
|
||||
is, the `<format>` header). Possible values are `1` when supported or `0` when unsupported.
|
||||
|
||||
## Default definition
|
||||
|
||||
The default value is detected based on the preprocessor macros `#!cpp JSON_HAS_CPP_20` and
|
||||
`#!cpp __cpp_lib_format`.
|
||||
|
||||
When the macro is not defined, the library will define it to its default value.
|
||||
|
||||
## Notes
|
||||
|
||||
!!! info "Enabled functionality"
|
||||
|
||||
When this macro evaluates to `1`, the library provides a
|
||||
[`std::formatter<basic_json>`](../basic_json/std_formatter.md) specialization so JSON values can be
|
||||
used directly with `std::format`.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
The code below forces the library to disable support for `std::format`, even if the standard library
|
||||
would otherwise support it:
|
||||
|
||||
```cpp
|
||||
#define JSON_HAS_STD_FORMAT 0
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
...
|
||||
```
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.12.x.
|
||||
Reference in New Issue
Block a user