From b2b47c69b1d99ae53bc8c40e1faab88ae729ef0d Mon Sep 17 00:00:00 2001 From: Niels Lohmann Date: Sat, 11 Jul 2026 23:58:49 +0200 Subject: [PATCH] :memo: Document std::pair/std::tuple conversion and C++20 range-view construction (#5271) Both had zero documentation anywhere in docs/mkdocs/. The tuple/pair gap was first spotted in the very first git-log audit pass but never turned into an actionable todo, so it persisted uncaught across four subsequent passes. - Document basic positional std::pair/std::tuple <-> json array conversion, plus #5016's reference-extraction capability (get>() returning references into the stored array elements). - Document #5205's new json-from-C++20-range-view constructor (e.g. nums | std::views::filter(...)). Signed-off-by: Niels Lohmann --- docs/mkdocs/docs/features/conversions.md | 36 ++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/docs/mkdocs/docs/features/conversions.md b/docs/mkdocs/docs/features/conversions.md index 9681cc114..be85f5db6 100644 --- a/docs/mkdocs/docs/features/conversions.md +++ b/docs/mkdocs/docs/features/conversions.md @@ -47,6 +47,28 @@ json j = {{"one", 1}, {"two", 2}}; auto m = j.get>(); // {{"one", 1}, {"two", 2}} ``` +`#!cpp std::pair` and `#!cpp std::tuple` are also supported, converting positionally to and from a JSON array: + +```cpp +json j = {1.0, "hello", 42}; +auto t = j.get>(); // {1.0, "hello", 42} +``` + +!!! info "Extracting references into a tuple" + + A tuple type may also hold references (e.g. `#!cpp std::tuple`) to avoid copying: `get` + then returns a tuple of references pointing directly at the elements stored inside the `basic_json` array, + rather than a tuple of copies: + + ```cpp + json j = {1.0, "hello"}; + auto refs = j.get>(); + std::get<1>(refs) = "world"; // modifies j[1] in place + ``` + + A referenced type must be one the library actually stores (or an arithmetic type it can convert to/from); + otherwise this is a compile error. + ## Implicit conversions By default, a JSON value implicitly converts to a compatible C++ type, so the explicit `get` call can often be omitted: @@ -136,6 +158,20 @@ std::vector numbers = {1, 2, 3}; json j = numbers; // [1,2,3] ``` +!!! info "Constructing from a C++20 range view" + + A `json` array can also be constructed directly from a C++20 range view (`std::ranges::view`), such as the result + of `std::views::filter` or `std::views::transform` -- no intermediate container is needed: + + ```cpp + std::vector nums{1, 2, 37, 42, 21}; + auto filtered = nums | std::views::filter([](int i) { return i > 10; }); + json j(filtered); // [37,42,21] + ``` + + This requires [`JSON_HAS_RANGES`](../api/macros/json_has_ranges.md) to be enabled and is unavailable on MinGW due + to incomplete C++20 ranges support there. + ## Your own types The conversions above are built in for standard types. To make the same syntax work for **your own** types, provide