GREsau / schemars

Generate JSON Schema documents from Rust code
https://graham.cool/schemars/
MIT License
791 stars 220 forks source link

Check if Value satisfies RootSchema #309

Open schneiderfelipe opened 1 month ago

schneiderfelipe commented 1 month ago

I would like to check whether a serde_json::Value satisfies a given RootSchema. Is this the right library or should I use e.g. jsonschema?

GREsau commented 1 month ago

It's possible schemars will get this feature in the future, but there's no immediate plans to implement such a feature yet - for now, the jsonschema crate is probably what you want.

You can, however, generate a JSON schema using schemars and then use jsonschema to validate a value against the schema. e.g. using schemars 1.0.0-alpha.3:

let schema = SchemaSettings::draft07()
    .into_generator()
    .into_root_schema_for::<MyStruct>();
let compiled = JSONSchema::compile(schema.as_value()).expect("A valid schema");

let instance = json!({ "foo": "bar" });

let result = compiled.validate(&instance);
if let Err(errors) = result {
    for error in errors {
        println!("Validation error: {}", error);
    }
}