quoted_num for numbers without quotes #1560
-
Hello, my use case is fairly simple, I need to support both quoted numbers and regular numbers when parsing json. I found quoted_num but that always expects quoted numbers and fails on regular numbers. I was thinking of using std::variant but I just want to use the values as ints at the end of the day. Thanks for any response.
I also need to alias width/height to max_width/max_height and what I have works but I wonder if there is a better solution now. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Here is an example that makes use of #include <iostream>
#include "glaze/glaze.hpp"
struct Command {
std::string action;
std::string preview_id;
std::string image_scaler;
int x = 0;
int y = 0;
int width = 0;
int height = 0;
};
template <>
struct glz::meta<Command> {
using T = Command;
template <auto MemberPointer>
static constexpr auto maybe_quoted_int_read = [](T& self, const glz::raw_json& json) {
// first attempt to parse without quotes
auto ec = glz::read_json(self.*MemberPointer, json.str);
if (ec) {
// if we error then attempt parsing as a quoted number
ec = glz::read<glz::opts{.quoted_num = true}>(self.*MemberPointer, json.str);
}
if (ec) {
throw std::runtime_error("maybe_quoted_int_read failure");
}
};
template <auto MemberPointer>
static constexpr auto custom_int = custom<maybe_quoted_int_read<MemberPointer>, MemberPointer>;
static constexpr auto value = object(
&T::action,
&T::preview_id,
&T::image_scaler,
"x", custom_int<&T::x>,
"y", custom_int<&T::y>,
"width", custom_int<&T::width>,
"height", custom_int<&T::height>,
"max_width", custom_int<&T::width>,
"max_height", custom_int<&T::height>
);
};
int main() {
Command obj{};
std::string input = R"({"x":55,"y":"77"})";
auto ec = glz::read_json(obj, input);
if (ec) {
std::cout << "parse error\n";
}
std::cout << glz::write_json(obj).value_or("error") << '\n';
return 0;
} Note that glz::custom currently must throw to handle errors. Let me know if this is an issue for you. |
Beta Was this translation helpful? Give feedback.
Here is an example that makes use of
glz::custom
to create custom handling that first tries to parse as a JSON number and then will parse as a JSON string if that fails. (Compiler Explorer Link: https://gcc.godbolt.org/z/Yh57caKvs)