Can generate JSON schemas
This commit is contained in:
49
src/lib.rs
49
src/lib.rs
@ -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
|
||||
|
@ -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()
|
||||
}
|
||||
|
Reference in New Issue
Block a user