Skip to content

Commit 7a6d53f

Browse files
committed
std::formatter specialisation for json objects
Signed-off-by: TymianekPL <tymi@tymi.org>
1 parent 44b0fee commit 7a6d53f

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

Test/Test.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,5 @@ int main()
55
{
66
cppjson::JsonObject object{};
77
object.As<std::string>() = "Purr world!";
8-
std::println("{}", object.As<std::string>());
8+
std::println("{}", object);
99
}

cppjson/include/cppjson/object.hpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <algorithm>
66
#include <string>
77
#include <cstddef>
8+
#include <format>
89

910
namespace cppjson
1011
{
@@ -38,5 +39,32 @@ namespace cppjson
3839
T& DangerousAs() noexcept { return *std::launder(reinterpret_cast<T*>(this->_dataStorage)); }
3940
template <typename T>
4041
const T& DangerousAs() const noexcept { return *std::launder(reinterpret_cast<T*>(this->_dataStorage)); }
42+
43+
friend struct std::formatter<cppjson::JsonObject>;
44+
};
45+
}
46+
47+
namespace std
48+
{
49+
template<>
50+
struct formatter<cppjson::JsonObject>
51+
{
52+
constexpr auto parse(std::format_parse_context& context)
53+
{
54+
return context.begin();
55+
}
56+
57+
auto format(const cppjson::JsonObject& object, std::format_context& context) const
58+
{
59+
switch (object._dataType)
60+
{
61+
case cppjson::JsonType::Null: return std::format_to(context.out(), "null");
62+
case cppjson::JsonType::Bool: return std::format_to(context.out(), "{}", object.DangerousAs<bool>());
63+
case cppjson::JsonType::Number: return std::format_to(context.out(), "{}", object.DangerousAs<double>());
64+
case cppjson::JsonType::String: return std::format_to(context.out(), "{}", object.DangerousAs<std::string>());
65+
}
66+
67+
throw std::logic_error("Unknown type");
68+
}
4169
};
4270
}

0 commit comments

Comments
 (0)