Enforce either Full or Empty Inner Object in JSON Schema #1831
Answered
by
stephenberry
StormLord07
asked this question in
Q&A
|
We have two structs, struct Inner {
std::string x;
std::string y;
};
struct Outer {
int x;
Inner inner;
int y;
};We want to support only JSONs that have the {"x": 1, "inner": {"x": "hello", "y": "world"}, "y": 2}or {"x": 1, "inner": {}, "y": 2}But not: {"x": 1, "inner": {"x": "hello"},"y": 2}or {"x": 1, "y": 2} The goal is to ensure that the As far i've read into optional but it doesnt seem like its the way because it will make it so if the inner is not in schema it will be accepted. |
Answered by
stephenberry
Jun 21, 2025
Replies: 1 comment
|
This is related to this issue: #1821. However, the constraint you want is supported because it is a constraint on your inner struct. Full demo: compiler explorer link #include <iostream>
#include "glaze/glaze.hpp"
struct Inner {
std::optional<std::string> x;
std::optional<std::string> y;
};
struct Outer {
int x;
Inner inner;
int y;
};
template <>
struct glz::meta<Outer> {
using T = Outer;
static constexpr auto inner_constraint = [](const T&, const Inner& inner) {
if (inner.x && inner.y) {
return true;
} else if ((not inner.x) && (not inner.y)) {
return true;
}
return false;
};
static constexpr auto value = object(
&T::x, //
"inner",
read_constraint<&T::inner, inner_constraint, "Both x and y must be included or excluded!">,
&T::y);
};
int main() {
Outer obj{};
std::string buffer = R"({"x": 1, "inner": {"x": "hello"},"y": 2})";
auto ec = glz::read_json(obj, buffer);
if (ec) {
std::cout << "Sucessful constraint error:\n";
std::cout << glz::format_error(ec, buffer) << '\n';
}
buffer = R"({"x": 1, "inner": {"x": "hello", "y": "world"}, "y": 2})";
ec = glz::read_json(obj, buffer);
if (ec) {
std::cout << glz::format_error(ec, buffer) << '\n';
}
else {
std::cout << "Success!\n";
}
return 0;
} |
0 replies
Answer selected by
StormLord07
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is related to this issue: #1821. However, the constraint you want is supported because it is a constraint on your inner struct.
Full demo: compiler explorer link