Option for making fields required by default when writing a schema #1571
-
|
Hello, would it be possible to add an option to make fields required by default when generating a JSON schema? Something like this: struct MyObject {
struct Child {
string a_field;
} child;
};
// Set `child` and `a_field` as required in the generated schema:
auto schema = glz::write_json_schema<MyObject, glz::opts{.require_all_fields = true}>();Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
This would be an excellent compile time option. I have plans to greatly improve the compile time option handling in Glaze, so I will probably wait until that is completed before adding this feature, as every new option currently makes template errors harder to read. I'll create an issue from this discussion to add this in the future. |
Beta Was this translation helpful? Give feedback.
-
|
This feature is was merged some time ago. You can use Example #include <glaze/glaze.hpp>
struct Address
{
std::string street{};
std::string city{};
std::optional<std::string> apartment{}; // nullable - will NOT be required
};
struct Person
{
std::string name{};
int age{};
std::optional<std::string> nickname{}; // nullable - will NOT be required
Address address{};
};
int main()
{
// Generate schema with all non-nullable fields marked as required
auto schema = glz::write_json_schema<Person, glz::opts{.error_on_missing_keys = true}>().value_or("error");
std::cout << glz::prettify_json(schema) << '\n';
}Output {
"type": ["object"],
"properties": {
"name": { "$ref": "#/$defs/std::string" },
"age": { "$ref": "#/$defs/int32_t" },
"nickname": { "$ref": "#/$defs/std::optional<std::string>" },
"address": { "$ref": "#/$defs/Address" }
},
"additionalProperties": false,
"$defs": {
"std::string": { "type": ["string"] },
"int32_t": { "type": ["integer"], "minimum": -2147483648, "maximum": 2147483647 },
"std::optional<std::string>": { "type": ["string", "null"] },
"Address": {
"type": ["object"],
"properties": {
"street": { "$ref": "#/$defs/std::string" },
"city": { "$ref": "#/$defs/std::string" },
"apartment": { "$ref": "#/$defs/std::optional<std::string>" }
},
"additionalProperties": false,
"required": ["street", "city"]
}
},
"required": ["name", "age", "address"],
"title": "Person"
}This works recursively for nested objects as well. |
Beta Was this translation helpful? Give feedback.
This feature is was merged some time ago. You can use
glz::opts{.error_on_missing_keys = true}when callingwrite_json_schemato mark all non-nullable fields as required in the generated schema.Example