core-adapters 0.1.2
Third-party adapters for snicholls-core: nanobind helpers, nlohmann/json hooks, the snicholls_core Python package
Loading...
Searching...
No Matches
json.hpp
Go to the documentation of this file.
1//
2// json.hpp
3// core-adapters
4//
5// Copyright 2010-2026 Saxon Herschel Nicholls
6//
7
55
58
59#ifndef snicholls_core_adapters_nlohmann_json_hpp
60#define snicholls_core_adapters_nlohmann_json_hpp
61
62#include <stdexcept>
63#include <string>
64#include <string_view>
65
66#include <nlohmann/json.hpp>
67
68namespace snicholls {
69
75struct json_error : std::runtime_error
76{
79 explicit json_error(const std::string& what) : std::runtime_error(what) {}
80};
81
82namespace detail {
83
84// "<type> from_json: <what> "<input>"" with the input cut at 64 characters, built out of line from the hot path.
85[[noreturn]] inline void throw_json_error(std::string_view type, std::string_view what, std::string_view input)
86{
87 constexpr std::size_t max_quoted = 64;
88 std::string message(type);
89 message += " from_json: ";
90 message += what;
91 message += " \"";
92 message += input.substr(0, max_quoted);
93 if (input.size() > max_quoted) message += "...";
94 message += '"';
95 throw json_error(message);
96}
97
98// The string a text-form adapter reads, or a json_error naming the JSON type it got instead. Never throws nlohmann.
99inline const std::string& json_string_or_throw(const nlohmann::json& j, std::string_view type, std::string_view expected)
100{
101 const auto* s = j.get_ptr<const nlohmann::json::string_t*>();
102 if (s == nullptr) [[unlikely]] {
103 std::string what("expected ");
104 what += expected;
105 what += ", got";
106 throw_json_error(type, what, j.type_name());
107 }
108 return *s;
109}
110
111} // namespace detail
112
113} // namespace snicholls
114
115#endif /* snicholls_core_adapters_nlohmann_json_hpp */
snicholls::json_error and the nlohmann/json adapter layer: shared by every adapter.
A JSON value that does not convert to or from a core type.
Definition json.hpp:76
json_error(const std::string &what)
Constructs it.
Definition json.hpp:79