Crate boon

source ·
Expand description

This crate supports JsonScehama validation for drafts 2020-12, 2019-09, 7, 6 and 4.

let mut schemas = Schemas::new(); // container for compiled schemas
let mut compiler = Compiler::new();
let sch_index = compiler.compile("schema.json", &mut schemas)?;
let instance: Value = serde_json::from_reader(File::open("instance.json")?)?;
let valid = schemas.validate(&instance, sch_index).is_ok();

If schema file has no $schema, it assumes latest draft. You can override this:

compiler.set_default_draft(Draft::V7);

The use of this option is HIGHLY encouraged to ensure continued correct operation of your schema. The current default value will not stay the same over time.

Examples

Compile Errors

println!("{compile_error}");
println!("{compile_error:#}"); // prints cause if any

Using alterate form in display will print cause if any. This will be useful in cases like CompileError::LoadUrlError, as it would be useful to know whether the url does not exist or the resource at url is not a valid json document.

Validation Errors

ValidationError may have multiple causes resulting in tree of errors.

println!("{validation_error}") prints:

jsonschema validation failed with file:///tmp/customer.json#
  at '': missing properties 'age'
  at '/billing_address': missing properties 'street_address', 'city', 'state'

The alternate form println!("{validation_error:#}") prints:

jsonschema validation failed with file:///tmp/customer.json#
  [I#] [S#/required] missing properties 'age'
  [I#/billing_address] [S#/properties/billing_address/$ref] validation failed with file:///tmp/address.json#
    [I#/billing_address] [S#/required] missing properties 'street_address', 'city', 'state'

here I refers to the instance document and S refers to last schema document.

for example:

  • after line 1: S refers to file:///tmp/customer.json
  • after line 3: S refers to file://tmp/address.json

Output Formats

ValidationError can be converted into following output formats:

  • flag validation_error.flag_output()
  • basic validation_error.basic_output()
  • detailed validation_error.detailed_output()

The output object implements serde::Serialize.

It also implement Display to print json:

println!("{output}"); // prints unformatted json
println!("{output:#}"); // prints indented json

Structs

Enums

Traits

  • A trait for loading json from given url