Repos
C++
1.4 KB51 lines Opens in site
Directory
Raw
Download
#pragma once
// Spec: SPEC.md FR-MOD-01 (tolerant decoding). Helpers over nlohmann::json.
#include <nlohmann/json.hpp>
#include <optional>
#include <string>
#include <vector>
namespace dp {
using Json = nlohmann::json;
class JsonRead {
public:
// Missing key, null or wrong type yields nullopt (unknown-key tolerant, same optionality as Swift).
template <class T>
static std::optional<T> opt(const Json& j, const char* key) {
if (!j.is_object()) return std::nullopt;
auto it = j.find(key);
if (it == j.end() || it->is_null()) return std::nullopt;
try {
return it->get<T>();
} catch (const Json::exception&) {
return std::nullopt;
}
}
template <class T>
static T get(const Json& j, const char* key, T fallback = T{}) {
auto v = opt<T>(j, key);
return v ? std::move(*v) : std::move(fallback);
}
static const Json* child(const Json& j, const char* key) {
if (!j.is_object()) return nullptr;
auto it = j.find(key);
if (it == j.end() || it->is_null()) return nullptr;
return &*it;
}
template <class T, class F>
static std::vector<T> list(const Json& j, const char* key, F&& decode) {
std::vector<T> out;
const Json* arr = child(j, key);
if (!arr || !arr->is_array()) return out;
out.reserve(arr->size());
for (const auto& item : *arr) out.push_back(decode(item));
return out;
}
};
} // namespace dp