3#include <nlohmann/json.hpp>
6#include <md/object.hpp>
17inline void to_nlohmann(nlohmann::json& j,
const Value& v);
19inline void to_nlohmann(nlohmann::json& j,
const Array& a) {
20 j = nlohmann::json::array();
21 for (
const auto& el : a) {
24 j.push_back(std::move(sub));
28inline void to_nlohmann(nlohmann::json& j,
const Object& o) {
29 j = nlohmann::json::object();
30 for (
const auto& [k, val] : o) {
32 to_nlohmann(sub, val);
33 j[k] = std::move(sub);
37inline void to_nlohmann(nlohmann::json& j,
const Value& v) {
40 }
else if (
const auto* pb = v.as_bool_if()) {
42 }
else if (
const auto* pi = v.as_int_if()) {
44 }
else if (
const auto* pu = v.as_uint_if()) {
46 }
else if (
const auto* pf = v.as_float_if()) {
48 }
else if (
const auto* pd = v.as_double_if()) {
50 }
else if (
const auto* ps = v.as_string_if()) {
52 }
else if (
const auto* pa = v.as_array_if()) {
54 }
else if (
const auto* po = v.as_object_if()) {
59inline Value from_nlohmann(
const nlohmann::json& j) {
61 case nlohmann::json::value_t::null:
63 case nlohmann::json::value_t::boolean:
64 return Value{j.get<
bool>()};
65 case nlohmann::json::value_t::number_unsigned:
66 return Value{j.get<std::uint64_t>()};
67 case nlohmann::json::value_t::number_integer:
68 return Value{j.get<std::int64_t>()};
69 case nlohmann::json::value_t::number_float:
70 return Value{j.get<
double>()};
71 case nlohmann::json::value_t::string:
72 return Value{j.get<std::string>()};
73 case nlohmann::json::value_t::array: {
76 for (
const auto& el : j) {
77 a.emplace_back(from_nlohmann(el));
79 return Value{std::move(a)};
81 case nlohmann::json::value_t::object: {
84 for (
auto it = j.begin(); it != j.end(); ++it) {
85 o.insert_or_assign(it.key(), from_nlohmann(it.value()));
87 return Value{std::move(o)};
90 throw type_error(
"md::from_json: unsupported nlohmann value type");
97inline void to_json(nlohmann::json& j,
const Value& v) {
98 detail::to_nlohmann(j, v);
101inline void from_json(
const nlohmann::json& j, Value& v) {
102 v = detail::from_nlohmann(j);
106inline void to_json(nlohmann::json& j,
const Object& o) {
107 detail::to_nlohmann(j, o);
111inline void from_json(
const nlohmann::json& j, Object& o) {
112 Value v = detail::from_nlohmann(j);
113 if (
auto* p = v.as_object_if()) {
116 throw type_error(
"md::from_json(Object): JSON value is not an object");
123[[nodiscard]]
inline nlohmann::json to_json(
const Value& v) {
125 detail::to_nlohmann(j, v);
129[[nodiscard]]
inline nlohmann::json to_json(
const Object& o) {
131 detail::to_nlohmann(j, o);
135[[nodiscard]]
inline Value from_json(
const nlohmann::json& j) {
136 return detail::from_nlohmann(j);