Skip to main content

Evaluation

Struct Evaluation 

Source
pub struct Evaluation { /* private fields */ }
Expand description

Result of evaluating a JSON instance against a schema.

This type provides access to structured output formats as defined in the JSON Schema specification.

§Output Formats

The evaluation result can be accessed in three standard formats:

  • Flag: Simple boolean validity indicator via flag()
  • List: Flat list of all evaluation units via list()
  • Hierarchical: Nested tree structure via hierarchical()

All formats are serializable to JSON using serde_json.

§Examples

use serde_json::json;

let schema = json!({"type": "string", "minLength": 3});
let validator = jsonschema::validator_for(&schema)?;

// Evaluate an instance
let instance = json!("ab");
let evaluation = validator.evaluate(&instance);

// Check validity with flag format
let flag = evaluation.flag();
assert!(!flag.valid);

// Get structured output as JSON
let list_output = serde_json::to_value(evaluation.list())?;
println!("{}", serde_json::to_string_pretty(&list_output)?);

// Iterate over errors
for error in evaluation.iter_errors() {
    println!("Error at {}: {}", error.instance_location, error.error);
}

Implementations§

Source§

impl Evaluation

Source

pub fn flag(&self) -> FlagOutput

Returns the flag output format.

This is the simplest output format, containing only a boolean indicating whether the instance is valid according to the schema.

§Examples
use serde_json::json;

let schema = json!({"type": "number"});
let validator = jsonschema::validator_for(&schema)?;

let evaluation = validator.evaluate(&json!(42));
let flag = evaluation.flag();
assert!(flag.valid);

let evaluation = validator.evaluate(&json!("not a number"));
let flag = evaluation.flag();
assert!(!flag.valid);
Source

pub fn is_valid(&self) -> bool

Whether the instance is valid against the schema.

§Examples
use serde_json::json;

let validator = jsonschema::validator_for(&json!({"type": "number"}))?;

assert!(validator.evaluate(&json!(42)).is_valid());
assert!(!validator.evaluate(&json!("oops")).is_valid());
Source

pub fn list(&self) -> ListOutput<'_>

Returns the list output format.

This format provides a flat list of all evaluation units, where each unit contains information about a specific validation step including its location, validity, annotations, and errors.

§Examples
use serde_json::json;

let schema = json!({
    "type": "array",
    "prefixItems": [{"type": "string"}],
    "items": {"type": "integer"}
});
let validator = jsonschema::validator_for(&schema)?;
let evaluation = validator.evaluate(&json!(["hello", "oops"]));

assert_eq!(
    serde_json::to_value(evaluation.list())?,
    json!({
        "valid": false,
        "details": [
            {"evaluationPath": "", "instanceLocation": "", "schemaLocation": "", "valid": false},
            {
                "valid": true,
                "evaluationPath": "/type",
                "instanceLocation": "",
                "schemaLocation": "/type"
            },
            {
                "valid": false,
                "evaluationPath": "/items",
                "instanceLocation": "",
                "schemaLocation": "/items",
                "droppedAnnotations": true
            },
            {
                "valid": false,
                "evaluationPath": "/items",
                "instanceLocation": "/1",
                "schemaLocation": "/items"
            },
            {
                "valid": false,
                "evaluationPath": "/items/type",
                "instanceLocation": "/1",
                "schemaLocation": "/items/type",
                "errors": {"type": "\"oops\" is not of type \"integer\""}
            },
            {
                "valid": true,
                "evaluationPath": "/prefixItems",
                "instanceLocation": "",
                "schemaLocation": "/prefixItems",
                "annotations": 0
            },
            {
                "valid": true,
                "evaluationPath": "/prefixItems/0",
                "instanceLocation": "/0",
                "schemaLocation": "/prefixItems/0"
            },
            {
                "valid": true,
                "evaluationPath": "/prefixItems/0/type",
                "instanceLocation": "/0",
                "schemaLocation": "/prefixItems/0/type"
            }
        ]
    })
);
Source

pub fn hierarchical(&self) -> HierarchicalOutput<'_>

Returns the hierarchical output format.

This format represents the evaluation as a tree structure that mirrors the schema’s logical structure. Each node contains its validation result along with nested child nodes representing sub-schema evaluations.

§Examples
use serde_json::json;

let schema = json!({
    "type": "array",
    "prefixItems": [{"type": "string"}],
    "items": {"type": "integer"}
});
let validator = jsonschema::validator_for(&schema)?;
let evaluation = validator.evaluate(&json!(["hello", "oops"]));

assert_eq!(
    serde_json::to_value(evaluation.hierarchical())?,
    json!({
        "valid": false,
        "evaluationPath": "",
        "schemaLocation": "",
        "instanceLocation": "",
        "details": [
            {
                "valid": true,
                "evaluationPath": "/type",
                "instanceLocation": "",
                "schemaLocation": "/type"
            },
            {
                "valid": false,
                "evaluationPath": "/items",
                "instanceLocation": "",
                "schemaLocation": "/items",
                "droppedAnnotations": true,
                "details": [
                    {
                        "valid": false,
                        "evaluationPath": "/items",
                        "instanceLocation": "/1",
                        "schemaLocation": "/items",
                        "details": [
                            {
                                "valid": false,
                                "evaluationPath": "/items/type",
                                "instanceLocation": "/1",
                                "schemaLocation": "/items/type",
                                "errors": {"type": "\"oops\" is not of type \"integer\""}
                            }
                        ]
                    }
                ]
            },
            {
                "valid": true,
                "evaluationPath": "/prefixItems",
                "instanceLocation": "",
                "schemaLocation": "/prefixItems",
                "annotations": 0,
                "details": [
                    {
                        "valid": true,
                        "evaluationPath": "/prefixItems/0",
                        "instanceLocation": "/0",
                        "schemaLocation": "/prefixItems/0",
                        "details": [
                            {
                                "valid": true,
                                "evaluationPath": "/prefixItems/0/type",
                                "instanceLocation": "/0",
                                "schemaLocation": "/prefixItems/0/type"
                            }
                        ]
                    }
                ]
            }
        ]
    })
);
Source

pub fn iter_annotations(&self) -> AnnotationIter<'_>

Returns an iterator over all annotations produced during evaluation.

Annotations are metadata emitted by keywords during successful validation. They can be used to collect information about which parts of a schema matched the instance.

§Examples
use serde_json::json;

let schema = json!({
    "type": "object",
    "properties": {"name": {"type": "string"}, "age": {"type": "number", "minimum": 0}},
    "required": ["name"]
});
let validator = jsonschema::validator_for(&schema)?;
let evaluation = validator.evaluate(&json!({"name": "Alice", "age": 30}));

let entries: Vec<_> = evaluation.iter_annotations().collect();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].schema_location, "/properties");
assert_eq!(entries[0].instance_location.as_str(), "");

let mut annotation_names: Vec<_> = entries[0]
    .annotations
    .value()
    .as_array()
    .expect("annotation should be an array")
    .iter()
    .map(|value| value.as_str().expect("annotation items should be strings"))
    .collect();
annotation_names.sort_unstable();
assert_eq!(annotation_names, vec!["age", "name"]);
Source

pub fn iter_errors(&self) -> ErrorIter<'_>

Returns an iterator over all errors produced during evaluation.

Each error entry contains information about a validation failure, including its location in both the schema and instance.

§Examples
use serde_json::json;

let schema = json!({
    "type": "object",
    "required": ["name"],
    "properties": {
        "age": {"type": "number"}
    }
});
let validator = jsonschema::validator_for(&schema)?;
let evaluation = validator.evaluate(&json!({"name": "Bob", "age": "oops"}));

let errors: Vec<_> = evaluation.iter_errors().collect();
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].schema_location, "/properties/age/type");
assert_eq!(errors[0].instance_location.as_str(), "/age");
assert_eq!(errors[0].error.to_string(), "\"oops\" is not of type \"number\"");

Trait Implementations§

Source§

impl Debug for Evaluation

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Inspect for T
where T: Debug,

Source§

fn inspect(&self) -> String

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Ungil for T
where T: Send,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more