xref: /openbmc/bmcweb/include/json_formatters.hpp (revision 40e9b92ec19acffb46f83a6e55b18974da5d708e)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 #pragma once
4 
5 #include <nlohmann/json.hpp>
6 
7 #include <format>
8 
9 // Clang-tidy would rather these be static, but using static causes the template
10 // specialization to not function.  Ignore the warning.
11 // NOLINTBEGIN(readability-convert-member-functions-to-static, cert-dcl58-cpp)
12 
13 template <>
14 struct std::formatter<nlohmann::json::json_pointer>
15 {
parsestd::formatter16     constexpr auto parse(std::format_parse_context& ctx)
17     {
18         return ctx.begin();
19     }
formatstd::formatter20     auto format(const nlohmann::json::json_pointer& ptr, auto& ctx) const
21     {
22         return std::format_to(ctx.out(), "{}", ptr.to_string());
23     }
24 };
25 
26 template <>
27 struct std::formatter<nlohmann::json>
28 {
parsestd::formatter29     static constexpr auto parse(std::format_parse_context& ctx)
30     {
31         return ctx.begin();
32     }
formatstd::formatter33     auto format(const nlohmann::json& json, auto& ctx) const
34     {
35         return std::format_to(
36             ctx.out(), "{}",
37             json.dump(-1, ' ', false,
38                       nlohmann::json::error_handler_t::replace));
39     }
40 };
41 // NOLINTEND(readability-convert-member-functions-to-static, cert-dcl58-cpp)
42