Can generate JSON schemas

This commit is contained in:
2023-02-28 15:09:01 +01:00
parent 97966c983a
commit 14c1955b15
4 changed files with 596 additions and 2 deletions

View File

@ -208,6 +208,55 @@ impl TreeNode {
r#enum: other.r#enum.or(self.r#enum),
}
}
/// Turn object into JSON schema
pub fn json_schema(&self) -> Value {
valico::json_schema::builder::schema(|s| self.json_schema_inner(s)).into_json()
}
fn json_schema_inner(&self, builder: &mut valico::json_schema::builder::Builder) {
if let Some(description) = &self.description {
builder.desc(description);
}
match &self.r#type {
NodeType::Null => {
builder.null();
}
NodeType::Boolean => {
builder.boolean();
}
NodeType::Array { item } => {
builder.array();
builder.items_schema(|b| Self::json_schema_inner(item, b));
}
NodeType::Object { children, required } => {
if let Some(required) = required {
builder.required(required.clone());
}
builder.properties(|properties| {
for child in children {
properties.insert(&child.name, |child_prop| {
Self::json_schema_inner(&child.node, child_prop);
});
}
});
}
NodeType::String => {
builder.string();
}
NodeType::Number => {
builder.number();
}
NodeType::Integer => {
builder.integer();
}
}
}
}
/// Construct the tree of a given structure name

View File

@ -34,6 +34,9 @@ enum Action {
/// Dump as JSON
Json,
/// Dump JSON schema
JsonSchema,
/// Dump as Graphviz graph
Graph,
@ -76,6 +79,7 @@ fn main() {
Action::Json => println!("{}", serde_json::to_string(&tree).unwrap()),
Action::Graph => println!("{}", graphviz_export(&tree)),
Action::Tex { .. } => println!("{}", tex_export(&tree)),
Action::JsonSchema => println!("{}", json_schema(&tree)),
}
}
@ -231,3 +235,7 @@ fn tex_export(tree: &TreeNode) -> String {
writeln!(out, "% END OF EXPORT OF SCHEMAS {}", tree.name).unwrap();
out
}
fn json_schema(tree: &TreeNode) -> String {
serde_json::to_string(&tree.json_schema()).unwrap()
}