From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Peter Johnson Date: Fri, 3 Apr 2026 23:05:58 -0700 Subject: [PATCH 20/25] Add array and object factory functions --- json.h | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/json.h b/json.h index d77ff1ea380614c54579d26cc233aa8424734b5b..08796527ea948c1cd602c0ba7a7b24dd75e57046 100644 --- a/json.h +++ b/json.h @@ -20,6 +20,8 @@ #include #include #include +#include +#include #include #include "wpi/util/StringMap.hpp" @@ -53,6 +55,13 @@ concept HasJsonDeserializer = requires (json& j, const json& cj, const T& val) { typename json_serializer>; { json_serializer>::from(cj) } -> std::convertible_to>; }; + +template +void apply_pairs_helper(F&& f, Tuple&& t, std::index_sequence) { + // This fold expression creates a sequence of calls to f for each pair + (f(std::get(std::forward(t)), + std::get(std::forward(t))), ...); +} } // namespace detail class json @@ -275,6 +284,27 @@ class json void set_array(); void set_object(); + template + static json array(Args&&... args) { + json j; + j.set_array(); + (j.array_value.emplace_back(std::forward(args)), ...); + return j; + } + + template + static json object(Args&&... args) { + json j; + j.set_object(); + detail::apply_pairs_helper( + [&](auto&& key, auto&& value) { + j.object_value[std::forward(key)] = std::forward(value); + }, + std::forward_as_tuple(args...), + std::make_index_sequence{}); + return j; + } + std::string to_string() const; std::string to_string_pretty() const;