Skip to main content

Crate rsonschema

Crate rsonschema 

Source
Expand description

§rsonschema

A fast, simple, user-friendly JSON Schema validator for Rust

§Usage

To use this crate, add it to your Cargo.toml running:

cargo add rsonschema

Then start using it in your code:

let schema = serde_json::json!({
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "minLength": 3
});

let instance = serde_json::json!("foo");
let report = rsonschema::validate(
    &instance,
    schema.clone(),
);
assert!(report.is_valid());

let instance = serde_json::json!("a");
let report = rsonschema::validate(
    &instance,
    schema,
);
assert_eq!(
    report,
    rsonschema::ValidationReport {
        errors: Some(
            rsonschema::error::ValidationErrors::from([
                rsonschema::error::ValidationError {
                    instance: serde_json::json!("a"),
                    type_: rsonschema::error::type_::ValidationErrorType::MinLength {
                        limit: 3.into(),
                    },
                    ..Default::default()
                }
            ])
        ),
        ..Default::default()
    }
);

§Contribute

§FAQ

§Too many arguments?

We doubted whether having such a large number of arguments on validate method was a correct choice. Currently we suppose this is the best option because every argument has its own differnt lifetime:

  • instance is the reference to the JSON instance to be validated and it is borrowed from the caller. It changes for every validation subschema
  • state is a mutable reference to the state of the validation process. It contains attributes that dont’t change during the validation process, such as the absolute schemas already encountered and the reference resolver
  • relative_schemas is a immutable reference to the relative schemas. It is fundamental for the $ref keyword. It is immutable because it is evaluated at the beginning the validation process for every new subschema
  • parent_id is a reference to the parent schema id It is fundamental for the $ref keyword. It is immutable because it changes at every validation subschema

Modules§

error
The module containing the error that may occurs while validating a JSON instance against a JSON schema
schema
The module containing the schema definitions

Structs§

ValidationReport
The report of the validation

Functions§

validate
Validate the given JSON instance against the schema
validate_with_resolver
Validate the given JSON instance against the schema using a custom reference resolver