Can I convert json or struct into JSON schema? #495
-
I want to create a basic JSON schema from a struct or a jsoncons::json. Is there already a function for this? If not, could you provide ideas on how I can implement it myself? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
We don't currently provide any support for that, and I haven't really thought about it. It's something we could look at as a new feature, but not likely any time soon. Our current focus with JSON Schema is on completing support for drafts 2019-09 and 2020-12. |
Beta Was this translation helpful? Give feedback.
-
Here's some code to get you started. #include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonschema/jsonschema.hpp>
#include <iostream>
using namespace jsoncons;
namespace jsonschema = jsoncons::jsonschema;
void generate_type_keyword(const json& value, json_string_encoder& encoder)
{
switch (value.type())
{
case json_type::object_value:
encoder.key("type");
encoder.string_value("object");
encoder.key("properties");
encoder.begin_object();
for (const auto& member : value.object_range())
{
encoder.key(member.key());
encoder.begin_object();
generate_type_keyword(member.value(), encoder);
encoder.end_object();
}
encoder.end_object();
break;
case json_type::string_value:
encoder.key("type");
encoder.string_value("string");
break;
default:
break;
}
}
void generate_schema(const json& data, json_string_encoder& encoder)
{
encoder.begin_object();
encoder.key("schema");
encoder.string_value("https://json-schema.org/draft/2020-12/schema");
encoder.key("id");
encoder.string_value("https://example.com/foo");
generate_type_keyword(data, encoder);
encoder.end_object();
encoder.flush();
}
int main()
{
std::string data_str = R"(
{
"foo" : {"bar" : "baz"}
}
)";
json data = json::parse(data_str);
std::string buffer;
json_string_encoder encoder(buffer);
generate_schema(data, encoder);
std::cout << buffer << "\n";
// A quick test, using code from master branch with preliminary draft 2020-12 support
json schema_document = json::parse(buffer);
auto schema = jsonschema::make_schema(schema_document);
jsonschema::json_validator validator(schema);
std::cout << "Is valid: " << validator.is_valid(data) << "\n";
} Output:
|
Beta Was this translation helpful? Give feedback.
We don't currently provide any support for that, and I haven't really thought about it. It's something we could look at as a new feature, but not likely any time soon. Our current focus with JSON Schema is on completing support for drafts 2019-09 and 2020-12.