### Install benchmark dependencies Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-rb/BENCHMARKS.md Installs the benchmark dependencies using Bundler. The --with benchmark flag includes the benchmark group. ```console $ bundle install --with benchmark ``` -------------------------------- ### Install dependencies with pip Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-py/BENCHMARKS.md Install the required dependencies for the benchmark suite. ```console $ pip install -e ".[bench]" ``` -------------------------------- ### Install jsonschema-rs Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-py/README.md Install the Python package from PyPI. ```bash pip install jsonschema-rs ``` -------------------------------- ### Install jsonschema-cli from source with cargo Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-cli/README.md Installs the CLI from source using Cargo, which requires Rust to be installed. ```bash cargo install jsonschema-cli ``` -------------------------------- ### Create virtual environment and install Python package in editable mode Source: https://github.com/stranger6667/jsonschema/blob/master/CONTRIBUTING.md Uses uv to create a virtual environment and install the package in editable mode with test dependencies. ```console $ uv venv $ uv pip install -e ".[tests]" ``` -------------------------------- ### HttpOptions usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/http.md Shows how to construct HttpOptions with a connect timeout, total timeout, and an extra root CA certificate. The example uses Duration::from_secs for timeouts and a path string for the certificate. ```rust use std::time::Duration; use jsonschema::HttpOptions; let http_options = HttpOptions::new() .connect_timeout(Duration::from_secs(10)) .timeout(Duration::from_secs(30)) .add_root_certificate("/path/to/ca-cert.pem"); ``` -------------------------------- ### bundle command example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/cli.md Bundles a schema into a compound document, registering an external resource and writing output to a file. ```console $ jsonschema bundle schema.json --resource https://example.com/x.json=./x.json -o bundled.json ``` -------------------------------- ### Location usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/paths.md Shows how to create a `Location` by joining segments, and verifies the pointer string and serialization. The example uses `Location::new()`, `join` with property and index segments, and asserts the resulting pointer. ```rust use jsonschema::paths::Location; let mut path = Location::new(); path = path.join("properties"); path = path.join("name"); assert_eq!(path.as_str(), "/properties/name"); // Display and Serialize both render the pointer assert_eq!(path.to_string(), "/properties/name"); assert_eq!(serde_json::to_string(&path)?, "\"/properties/name\""); # Ok::<(), Box>(()) ``` -------------------------------- ### Canonicalize unsatisfiable schema example Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-cli/README.md Shows that a schema no value can satisfy collapses to false, written as {"not": {}}. The example includes the shell command and the output. ```console $ echo '{"type": "integer", "minimum": 10, "maximum": 5}' > empty.json $ jsonschema canonicalize empty.json { "$schema": "https://json-schema.org/draft/2020-12/schema", "not": {} } ``` -------------------------------- ### Authentication-free local use example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/referencing.md Shows how to build a registry with a local resource and validate a schema that references it. Uses Registry::new(), add(), prepare(), and jsonschema::options().with_registry(). ```rust # fn main() -> Result<(), Box> { use jsonschema::{Registry, Resource}; use serde_json::json; let registry = Registry::new() .add("https://example.com/root", Resource::from_contents(json!({ "$id": "https://example.com/root", "definitions": {"User": {"type": "object", "required": ["name"]}} })))? .prepare()?; let user_schema = json!({"$ref": "https://example.com/root#/definitions/User"}); let validator = jsonschema::options() .with_registry(®istry) .build(&user_schema)?; assert!(validator.is_valid(&json!({"name": "Alice"}))); assert!(!validator.is_valid(&json!({}))); # Ok(()) } # } ``` -------------------------------- ### meta module usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/meta.md Usage example for the `meta` module: validates a valid schema with `is_valid`, checks an invalid schema with `validate`, and uses `validator_for` to create a reusable validator that evaluates a schema. The example uses `serde_json::json!` and returns `Ok` with a boxed error. ```rust use serde_json::json; let schema = json!({ "type": "object", "properties": {"age": {"type": "integer", "minimum": 0}} }); assert!(jsonschema::meta::is_valid(&schema)); let invalid = json!({"type": "invalid_type", "minimum": "not_a_number"}); assert!(jsonschema::meta::validate(&invalid).is_err()); let validator = jsonschema::meta::validator_for(&json!({"type": "string"}))?; assert!(validator.evaluate(&json!({"type": "string"})).flag().valid); # Ok::<(), Box>(()) ``` -------------------------------- ### validate usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/lib.md Example usage of `validate` with a minimum constraint. The match prints the instance path and error message when validation fails. ```rust use serde_json::json; let schema = json!({"minimum": 5}); match jsonschema::validate(&schema, &json!(3)) { Ok(()) => unreachable!(), Err(e) => println!("at {}: {}", e.instance_path(), e), } ``` -------------------------------- ### Example: subtract to compare two schema versions Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/canonical.md Shows how to use the subtract method to compare two schema versions. It canonicalizes two schemas with different minLength constraints, subtracts the second from the first, and checks the satisfiability of the result to determine if any values were removed. The example prints 'nothing was removed' if the result is unsatisfiable, otherwise 'behavior changed'. ```rust use serde_json::json; let before = jsonschema::canonicalize(&json!({"type": "string", "minLength": 3})).unwrap(); let after = jsonschema::canonicalize(&json!({"type": "string", "minLength": 5})).unwrap(); // Values accepted before but not after let removed = before.subtract(&after).expect("compatible operands"); match removed.satisfiability() { jsonschema::canonical::Satisfiability::No => println!("nothing was removed"), _ => println!("behavior changed"), } ``` -------------------------------- ### validate command examples Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/cli.md Shows three example invocations of the validate subcommand: basic validation, multiple instances with flag output and errors-only, and draft enforcement with timeout. ```console $ jsonschema validate schema.json -i instance.json ``` ```console $ jsonschema validate -i a.json b.json --output flag --errors-only schema.json ``` ```console $ jsonschema validate schema.json --draft 2020-12 --timeout 30 ``` -------------------------------- ### Install jsonschema-cli on Linux/macOS Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-cli/README.md Downloads the latest Linux x86_64 GNU binary from the releases page, extracts it, and moves it to /usr/local/bin/. Replace VERSION with the actual release version. ```bash curl -LO https://github.com/Stranger6667/jsonschema-rs/releases/download/VERSION/jsonschema-cli-x86_64-unknown-linux-gnu.tar.gz tar xzf jsonschema-cli-x86_64-unknown-linux-gnu.tar.gz sudo mv jsonschema-cli /usr/local/bin/ ``` -------------------------------- ### AsyncHttpRetriever usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/http.md Shows how to build a validator with an async HTTP retriever using jsonschema::async_options().with_retriever(). The example uses a $ref to a remote schema and validates a JSON value. ```rust # #[cfg(all(feature = "resolve-http", feature = "resolve-async"))] # async fn example() -> Result<(), Box> { use serde_json::json; let validator = jsonschema::async_options() .with_retriever(jsonschema::AsyncHttpRetriever::new(&jsonschema::HttpOptions::new())?) .build(&json!({"$ref": "https://example.com/user.json"})) .await?; assert!(validator.is_valid(&json!({"name": "A"}))); # Ok(()) } # } ``` -------------------------------- ### Install jsonschema_rs gem Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-rb/README.md Add the gem to your Gemfile to install the jsonschema_rs Ruby gem. Pre-built native gems are available for Linux, macOS, and Windows; on other platforms, gem install compiles from source and requires Ruby 3.2+ and a Rust toolchain. ```ruby gem 'jsonschema_rs' ``` -------------------------------- ### Canonicalize allOf example: input and output Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-cli/README.md Demonstrates canonicalizing a schema with allOf branches. The input pet.yaml is shown, then the canonicalized output after running jsonschema canonicalize. ```console $ cat pet.yaml allOf: - type: object properties: {name: {type: string}} required: [name] - type: object properties: {age: {type: integer, minimum: 0}} ``` ```json $ jsonschema canonicalize pet.yaml { "$schema": "https://json-schema.org/draft/2020-12/schema", "properties": { "age": {"minimum": 0, "type": "integer"}, "name": {"type": "string"} }, "required": ["name"], "type": "object" } ``` -------------------------------- ### Configure regex engine with PatternOptions Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/options.md Shows how to configure the regex engine via with_pattern_options. The example sets a backtrack_limit of 10_000 to reject catastrophic-backtracking regexes early; the commented alternative uses PatternOptions::regex(). ```rust use jsonschema::PatternOptions; let validator = jsonschema::options() // Reject catastrophic-backtracking regexes early .with_pattern_options(PatternOptions::fancy_regex().backtrack_limit(10_000)) // or: .with_pattern_options(PatternOptions::regex()) .build(&serde_json::json!({"type": "string", "pattern": "^(a+)+$"})) .expect("valid schema"); ``` -------------------------------- ### Annotations usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/evaluation.md Example demonstrating how to use the Annotations feature of the jsonschema crate in Rust. It shows creating a validator, evaluating an instance, and iterating over annotations to inspect schema locations and annotation values. ```APIDOC ## Annotations usage example ```rust # fn main() -> Result<(), Box> { use serde_json::json; let validator = jsonschema::validator_for(&json!({ "type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "number"}} }))?; let evaluation = validator.evaluate(&json!({"name": "Alice", "age": 30})); let entry = evaluation.iter_annotations().next().unwrap(); assert_eq!(entry.schema_location, "/properties"); assert_eq!(entry.instance_location.as_str(), ""); let mut names: Vec<_> = entry.annotations.value().as_array().unwrap().iter() .map(|v| v.as_str().unwrap()).collect(); names.sort_unstable(); assert_eq!(names, vec!["age", "name"]); # Ok(()) } # } ``` ``` -------------------------------- ### Registry::new() Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/referencing.md Creates a new RegistryBuilder to start building a registry. ```APIDOC ## Registry::new() ### Description Starts building a registry by returning a new RegistryBuilder. ### Method new ### Signature pub fn new<'b>() -> RegistryBuilder<'b> ### Returns - **RegistryBuilder<'b>** - A builder for constructing a Registry. ### Source crates/jsonschema-referencing/src/registry/mod.rs:251 ``` -------------------------------- ### Example: iterating errors with iter_errors Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/evaluation.md Shows how to use `validator.evaluate` and `iter_errors` to access error entries. The example asserts the schema location is `/required` and prints the error message. ```rust # fn main() -> Result<(), Box> { use serde_json::json; let validator = jsonschema::validator_for(&json!({"required": ["name"], "properties": {"a": {"type": "string"}}}))?; let evaluation = validator.evaluate(&json!({})); let mut errors = evaluation.iter_errors(); if let Some(entry) = errors.next() { assert_eq!(entry.schema_location, "/required"); println!("{}", entry); // at root: "\"name\" is a required property" } # Ok(()) } # } ``` -------------------------------- ### Install with mold linker on Linux Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-py/README.md Use this command when a source build on Linux fails with linking errors (e.g., undefined symbols from ring). It sets the RUSTFLAGS environment variable to use the mold linker and forces a source build with --no-binary :all:. ```bash RUSTFLAGS="-C link-arg=-fuse-ld=mold" \ pip install jsonschema-rs --no-binary :all: ``` -------------------------------- ### LocationSegment usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/paths.md Demonstrates constructing a `Location` using `LocationSegment::Property` and `LocationSegment::Index`, resulting in the pointer `/items/3`. ```rust use jsonschema::paths::{Location, LocationSegment}; let items = Location::new().join(LocationSegment::Property("items")).join(LocationSegment::Index(3)); assert_eq!(items.as_str(), "/items/3"); ``` -------------------------------- ### Canonicalize const example Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-cli/README.md Shows that equivalent schemas canonicalize to the same form, here a schema with a const constraint. ```json {"$schema": "https://json-schema.org/draft/2020-12/schema", "const": 1} ``` -------------------------------- ### canonicalize usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/lib.md Example showing that two different schemas with the same semantics canonicalize to the same schema. The interval schema and the constant schema produce equal `to_json_schema()` output. ```rust use serde_json::json; let interval = jsonschema::canonicalize(&json!({"type": "integer", "minimum": 1, "maximum": 1})).unwrap(); let constant = jsonschema::canonicalize(&json!({"const": 1, "type": "integer"})).unwrap(); assert_eq!(interval.to_json_schema(), constant.to_json_schema()); ``` -------------------------------- ### Draft detection usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/referencing.md Shows how to use `Draft::from_schema_uri` and `Draft::detect` to determine the draft from a schema URI or a `$schema` field. The example asserts that `http://json-schema.org/draft-07/schema#` maps to `Draft::Draft7`, the default is `Draft202012`, and a `$schema` of `https://json-schema.org/draft/2019-09/schema` is detected as `Draft201909`. ```rust use jsonschema::Draft; assert_eq!(Draft::from_schema_uri("http://json-schema.org/draft-07/schema#"), Draft::Draft7); assert_eq!(Draft::default(), Draft::Draft202012); let schema = serde_json::json!({"$schema": "https://json-schema.org/draft/2019-09/schema", "type": "string"}); assert_eq!(Draft::default().detect(&schema), Draft::Draft201909); ``` -------------------------------- ### dereference command example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/cli.md Dereferences a schema, inlining all $ref targets. Leaves circular references as $ref strings. ```console $ jsonschema dereference schema.json ``` -------------------------------- ### Example list output from evaluate() with prefixItems and items Source: https://github.com/stranger6667/jsonschema/blob/master/MIGRATION.md Shows the JSON Schema Output v1 list format produced when evaluating an array against a schema with prefixItems and items. The output includes details for each evaluation step, with valid flags, evaluation paths, instance locations, schema locations, and optional errors or annotations. ```json { "valid": false, "details": [ {"valid": false, "evaluationPath": "", "schemaLocation": "", "instanceLocation": ""}, { "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" }, { "valid": true, "evaluationPath": "/type", "instanceLocation": "", "schemaLocation": "/type" } ] } ``` -------------------------------- ### canonicalize command examples Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/cli.md Canonicalizes a schema, optionally targeting a subschema via JSON Pointer or enforcing a draft and writing to a file. ```console $ jsonschema canonicalize schema.json --at /$defs/Pet ``` ```console $ jsonschema canonicalize schema.json --draft 2020-12 -o canonical.json ``` -------------------------------- ### Building and using a validator with Draft7 Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/validator.md Example of building a validator with Draft7, checking validity, and iterating errors. Shows that is_valid returns false for an invalid instance and iter_errors prints each error with its instance path. ```rust # fn main() -> Result<(), Box> { use serde_json::json; let validator = jsonschema::options() .with_draft(jsonschema::Draft::Draft7) .build(&json!({ "type": "object", "properties": {"n": {"minimum": 5}}, "required": ["name"] }))?; assert_eq!(validator.draft(), jsonschema::Draft::Draft7); let instance = json!({"n": 1}); assert!(!validator.is_valid(&instance)); for error in validator.iter_errors(&instance) { println!("{} at {}", error, error.instance_path()); } # Ok(()) } # } ``` -------------------------------- ### Using validator_map_for with ValidatorMap Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/validator.md Example usage of validator_map_for to build a ValidatorMap from a JSON schema. It demonstrates contains_key, get, and is_valid. Note that indexing panics on absent keys, so get() is recommended. ```rust # fn main() -> Result<(), Box> { use serde_json::json; let map = jsonschema::validator_map_for(&json!({ "$defs": {"User": {"type": "object", "required": ["name"]}} }))?; assert!(map.contains_key("#/$defs/User")); // Indexing panics on absent keys — use get() to check first let user = map.get("#/$defs/User").expect("User compiled"); assert!(!user.is_valid(&json!({}))); # Ok(()) } # } ``` -------------------------------- ### Create a JSONSchema Registry and validate a $ref Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-rb/README.md Creates a Registry with two schemas and validates a document that references the address schema via $ref. The registry resolves the $ref locally without fetching, and the example shows the expected true result. ```ruby registry = JSONSchema::Registry.new([ ["https://example.com/address.json", { "type" => "object", "properties" => { "street" => { "type" => "string" }, "city" => { "type" => "string" } } }], ["https://example.com/person.json", { "type" => "object", "properties" => { "name" => { "type" => "string" }, "address" => { "$ref" => "https://example.com/address.json" } } }] ]) validator = JSONSchema.validator_for( { "$ref" => "https://example.com/person.json" }, registry: registry ) validator.valid?({ "name" => "John", "address" => { "street" => "Main St", "city" => "Boston" } }) # => true ``` -------------------------------- ### Canonicalization usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/canonical.md Shows canonicalization of equivalent schemas, detection of unsatisfiable schemas, and enum normalization. Uses `canonicalize` from `jsonschema::canonical` and `serde_json::json`. The example asserts that `{"type": "integer", "minimum": 1, "maximum": 1}` and `{"const": 1, "type": "integer"}` canonicalize to the same schema, that an empty range yields `Satisfiability::No`, and that an enum with duplicates is normalized to sorted unique values. ```rust use jsonschema::{canonical::{CanonicalKind, CanonicalView, Satisfiability}, canonicalize}; use serde_json::json; let interval = canonicalize(&json!({"type": "integer", "minimum": 1, "maximum": 1})).unwrap(); let constant = canonicalize(&json!({"const": 1, "type": "integer"})).unwrap(); assert_eq!(interval.to_json_schema(), constant.to_json_schema()); let empty = canonicalize(&json!({"type": "integer", "minimum": 10, "maximum": 5})).unwrap(); assert_eq!(empty.satisfiability(), Satisfiability::No); match canonicalize(&json!({"enum": [2, 1, 2, 9]})).unwrap().view() { CanonicalView::Enum(values) => assert_eq!(values, vec![json!(1), json!(2), json!(9)]), other => panic!("expected enum, got {other:?}"), } ``` -------------------------------- ### Collect and print validation errors Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/error.md Example of using `iter_errors` to collect errors and print them. The `Display` output starts with `Validation errors:` and numbered lines like `01: ...`. ```rust let errors = validator.iter_errors(&instance).into_errors(); println!("{errors}"); // "Validation errors:\n 01: ..." ``` -------------------------------- ### Find dead subschemas with find_unsatisfiable Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-py/README.md Walks a document and reports each subschema that accepts no value, returning reasons keyed by JSON pointer. The example shows a Conflict reason with the keywords at fault and confirms a live subschema is not reported. ```python from jsonschema_rs.canonical import UnsatisfiableReason, find_unsatisfiable reasons = find_unsatisfiable({ "properties": { "tag": {"type": "string", "minLength": 5, "maxLength": 2}, "name": {"type": "string"}, } }) match reasons["/properties/tag"]: case UnsatisfiableReason.Conflict(causes): assert [(cause.pointer, cause.keywords) for cause in causes] == [ ("/properties/tag", ["type"]), ("/properties/tag", ["minLength", "maxLength"]), ] # A live subschema is not reported assert "/properties/name" not in reasons ``` -------------------------------- ### RegistryBuilder::prepare() Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/referencing.md Compiles the store into a Registry, validating resources and building resolvers. ```APIDOC ## RegistryBuilder::prepare() ### Description Compiles the builder into a `Registry`, validating resources and building resolvers. Returns errors for draft, vocabulary, or resolution problems such as `UnknownSpecification` or `Unretrievable`. ### Method prepare ### Signature pub fn prepare(self) -> Result, Error> ### Returns - **Result, Error>** - The prepared registry or an error. ### Source crates/jsonschema-referencing/src/registry/mod.rs:187 ``` -------------------------------- ### Build validator with custom format and draft Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/options.md Builds a validator with a custom format and draft, then checks validation results. Requires the `serde_json` and `jsonschema` crates. The `with_format` closure returns a boolean; `should_validate_formats(true)` enables format validation. The example asserts that "Hello 42" is valid and "No!" is not. ```rust # fn main() -> Result<(), Box> { use serde_json::json; use jsonschema::Draft; let schema = json!({"type": "string", "format": "ends-with-42"}); let validator = jsonschema::options() .with_draft(Draft::Draft202012) .with_format("ends-with-42", |s| s.ends_with("42")) .should_validate_formats(true) .build(&schema)?; assert!(validator.is_valid(&json!("Hello 42"))); assert!(!validator.is_valid(&json!("No!"))); # Ok(()) } # } ``` -------------------------------- ### evaluate usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/lib.md Example usage of `evaluate` with a number type schema. The assertion checks the flag output is valid. ```rust use serde_json::json; let evaluation = jsonschema::evaluate(&json!({"type": "number"}), &json!(1)); assert!(evaluation.flag().valid); ``` -------------------------------- ### HttpOptions::new Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/http.md Creates a new HttpOptions instance with default settings. ```APIDOC ## `HttpOptions::new` ### Description Creates a new `HttpOptions` instance with default settings. ### Method `new` ### Signature rust #[must_use] pub fn new() -> Self ### Parameters None. ### Returns `HttpOptions` - A new instance with default configuration. ### Example rust use jsonschema::HttpOptions; let options = HttpOptions::new(); ``` -------------------------------- ### is_valid usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/lib.md Example usage of `is_valid` with a simple string schema. The first assertion passes, the second fails because the instance is a number. ```rust use serde_json::json; assert!(jsonschema::is_valid(&json!({"type": "string"}), &json!("hi"))); assert!(!jsonschema::is_valid(&json!({"type": "string"}), &json!(42))); ``` -------------------------------- ### Create a Registry and validate with $ref Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-py/README.md Shows how to create a jsonschema_rs.Registry with schemas keyed by URI, use it with validator_for to resolve $refs, and validate an instance. The registry holds schemas so validators resolve references without fetching. ```python import jsonschema_rs # Create a registry with schemas registry = jsonschema_rs.Registry([ ("https://example.com/address.json", { "type": "object", "properties": { "street": {"type": "string"}, "city": {"type": "string"} } }), ("https://example.com/person.json", { "type": "object", "properties": { "name": {"type": "string"}, "address": {"$ref": "https://example.com/address.json"} } }) ]) # Use the registry with any validator validator = jsonschema_rs.validator_for( {"$ref": "https://example.com/person.json"}, registry=registry ) # Validate instances assert validator.is_valid({ "name": "John", "address": {"street": "Main St", "city": "Boston"} }) ``` -------------------------------- ### dereference usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/lib.md Example of using `jsonschema::dereference` to resolve a local `$ref` to a `$defs` entry. The result's `properties.name.type` becomes `"string"`. ```rust use serde_json::json; let schema = json!({"$defs": {"tag": {"type": "string"}}, "properties": {"name": {"$ref": "#/$defs/tag"}}}); let result = jsonschema::dereference(&schema).expect("dereference failed"); assert_eq!(result["properties"]["name"]["type"], "string"); ``` -------------------------------- ### Run tests with uv Source: https://github.com/stranger6667/jsonschema/blob/master/examples/pyo3-extension/README.md Use `uv run test.py` to build and run the checks in `test.py`. The expected output is `ok`. ```console $ uv run test.py ok ``` -------------------------------- ### HttpOptions builder methods Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/http.md Lists the builder methods for HttpOptions: new, connect_timeout, timeout, danger_accept_invalid_certs, and add_root_certificate. Each returns Self for chaining. ```rust #[must_use] pub fn new() -> Self #[must_use] pub fn connect_timeout(mut self, timeout: Duration) -> Self #[must_use] pub fn timeout(mut self, timeout: Duration) -> Self #[must_use] pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self #[must_use] pub fn add_root_certificate(mut self, path: impl Into) -> Self ``` -------------------------------- ### Initialize and update git submodules for JSON Schema Test Suite Source: https://github.com/stranger6667/jsonschema/blob/master/CONTRIBUTING.md Run these commands to download the JSON Schema Test Suite, which is required for running the tests. The suite is cloned to `crates/jsonschema/tests/suite/`. ```console $ git submodule init $ git submodule update ``` -------------------------------- ### Registry construction migration (0.45.x to 0.46.0) Source: https://github.com/stranger6667/jsonschema/blob/master/MIGRATION.md Shows the old and new ways to build a registry and validator. In 0.46.0, build a Registry with add/extend and prepare(), then pass it by reference to with_registry. The old with_resource and with_resources methods are removed. ```rust // Old (0.45.x) use jsonschema::{Registry, Resource}; // Inline shared schema let validator = jsonschema::options() .with_resource( "https://example.com/schema", Resource::from_contents(shared_schema), ) .build(&schema)?; // Multiple shared schemas let validator = jsonschema::options() .with_resources([ ( "https://example.com/schema-1", Resource::from_contents(schema_1), ), ( "https://example.com/schema-2", Resource::from_contents(schema_2), ), ].into_iter()) .build(&schema)?; // Prebuilt registry let registry = Registry::try_from_resources([ ( "https://example.com/schema", Resource::from_contents(shared_schema), ), ])?; let validator = jsonschema::options() .with_registry(registry) .build(&schema)?; // New (0.46.0) use jsonschema::Registry; // Shared registry + borrowed validator build let registry = Registry::new() .add("https://example.com/schema", shared_schema)? .prepare()?; let validator = jsonschema::options() .with_registry(®istry) .build(&schema)?; // Multiple shared schemas let registry = Registry::new() .extend([ ("https://example.com/schema-1", schema_1), ("https://example.com/schema-2", schema_2), ])? .prepare()?; let validator = jsonschema::options() .with_registry(®istry) .build(&schema)?; ``` -------------------------------- ### options() Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/meta.md Creates a new MetaSchemaOptions builder with default settings. ```APIDOC ## `options()` ### Description Creates a new `MetaSchemaOptions` builder with default settings. ### Method `options` ### Signature `pub fn options<'a>() -> MetaSchemaOptions<'a>` ### Returns - `MetaSchemaOptions<'a>` - A new builder instance. ``` -------------------------------- ### Get collected errors from evaluation Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-rb/README.md Returns every error collected across all evaluation nodes. ```ruby evaluation.errors # => [{schemaLocation: "/required", absoluteKeywordLocation: nil, # instanceLocation: "", error: "\"name\" is a required property"}, # {schemaLocation: "/properties/age/type", absoluteKeywordLocation: nil, # instanceLocation: "/age", # error: "\"not_an_integer\" is not of type \"integer\""}] ``` -------------------------------- ### Simplify Registry API with builder pattern (0.28.x to 0.29.0) Source: https://github.com/stranger6667/jsonschema/blob/master/MIGRATION.md Shows the simplified Registry API when upgrading from 0.28.x to 0.29.0. Replace direct creation methods (`try_new`, `try_from_resources`, `try_with_resource_and_retriever`) with `Registry::options()` and the consistent builder pattern using `.build()`. ```rust // Before (0.28.x) let registry = Registry::options() .draft(Draft::Draft7) .try_new( "http://example.com/schema", resource )?; let registry = Registry::options() .draft(Draft::Draft7) .try_from_resources([ ("http://example.com/schema", resource) ].into_iter())?; let registry = Registry.try_with_resource_and_retriever( "http://example.com/schema", resource, retriever )?; // After (0.29.0) let registry = Registry::options() .draft(Draft::Draft7) .build([ ("http://example.com/schema", resource) ])?; let registry = Registry::options() .draft(Draft::Draft7) .build([ ("http://example.com/schema", resource) ])?; let registry = Registry::options() .retriever(retriever) .build(resources)?; ``` -------------------------------- ### jsonschema bundle command usage Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-cli/README.md Shows the basic command-line usage for the bundle subcommand, which embeds all $ref targets into a draft-appropriate container. ```console jsonschema bundle [OPTIONS] ``` -------------------------------- ### ValidationError usage example Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/error.md Demonstrates validating a JSON instance, accessing error details, and using masking. ```rust # fn main() -> Result<(), Box> { use serde_json::json; let validator = jsonschema::validator_for(&json!({ "properties": {"name": {"type": "string", "minLength": 3}} }))?; let error = validator.validate(&json!({"name": "ab"})).expect_err("invalid"); println!("message: {error}"); println!("instance: {}", error.instance()); println!("kind: {:?}", error.kind()); println!("instance: {}", error.instance_path()); // /name println!("schema: {}", error.schema_path()); // /properties/name/minLength println!("masked: {}", error.masked()); // "ab" replaced with "value" let parts = error.into_parts(); assert_eq!(parts.instance_path.as_str(), "/name"); # Ok(()) } # } ``` -------------------------------- ### Run benchmarks with cargo bench Source: https://github.com/stranger6667/jsonschema/blob/master/crates/benchmark-suite/README.md Run the benchmark suite to compare Rust JSON Schema implementations. The command is executed from the crate root. ```console $ cargo bench ``` -------------------------------- ### jsonschema bundle with local resource Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-cli/README.md Registers an external schema resource via --resource so that references to https://example.com/address.json are resolved locally. ```console jsonschema bundle root.json --resource https://example.com/address.json=address.json ``` -------------------------------- ### Build and run Ruby extension tests Source: https://github.com/stranger6667/jsonschema/blob/master/examples/magnus-extension/README.md Builds the Ruby extension and runs the checks in test.rb. The output 'ok' indicates the tests passed. ```console $ bundle install $ bundle exec rake compile $ bundle exec ruby test.rb ok ``` -------------------------------- ### Get hierarchical output from evaluation Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-rb/README.md Returns the hierarchical output format, which nests evaluation nodes by schema structure. ```ruby evaluation.hierarchical # => {valid: false, evaluationPath: "", schemaLocation: "", instanceLocation: "", # details: [ # {valid: true, evaluationPath: "/type", schemaLocation: "/type", instanceLocation: ""}, # {valid: false, evaluationPath: "/required", schemaLocation: "/required", # instanceLocation: "", # errors: {"required" => "\"name\" is a required property"}}, # {valid: false, evaluationPath: "/properties", schemaLocation: "/properties", # instanceLocation: "", droppedAnnotations: ["age"], # details: [ # {valid: false, evaluationPath: "/properties/age", # schemaLocation: "/properties/age", instanceLocation: "/age", # details: [ # {valid: false, evaluationPath: "/properties/age/type", # schemaLocation: "/properties/age/type", instanceLocation: "/age", # errors: {"type" => "\"not_an_integer\" is not of type \"integer\""}} # ]} # ]} # ]} ``` -------------------------------- ### Get flag output from evaluation Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-rb/README.md Returns the flag output format, which is either valid or invalid with no additional details. ```ruby evaluation.flag # => {valid: false} ``` -------------------------------- ### Get list output from evaluation Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-rb/README.md Returns the list output format, which contains every evaluation node in a flat list. ```ruby evaluation.list # => {valid: false, # details: [ # {valid: false, evaluationPath: "", schemaLocation: "", instanceLocation: ""}, # {valid: true, evaluationPath: "/type", schemaLocation: "/type", instanceLocation: ""}, # {valid: false, evaluationPath: "/required", schemaLocation: "/required", # instanceLocation: "", # errors: {"required" => "\"name\" is a required property"}}, # {valid: false, evaluationPath: "/properties", schemaLocation: "/properties", # instanceLocation: "", droppedAnnotations: ["age"]}, # {valid: false, evaluationPath: "/properties/age", schemaLocation: "/properties/age", # instanceLocation: "/age"}, # {valid: false, evaluationPath: "/properties/age/type", # schemaLocation: "/properties/age/type", instanceLocation: "/age", # errors: {"type" => "\"not_an_integer\" is not of type \"integer\""}} # ]} ``` -------------------------------- ### CanonicalizeOptions::with_registry Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/canonical.md Sets a prebuilt registry for dialect and `$ref` resolution. ```APIDOC ## `CanonicalizeOptions::with_registry` ### Description Sets a prebuilt registry for dialect and `$ref` resolution. ### Method Builder method ### Endpoint `CanonicalizeOptions::with_registry(registry: &'r Registry<'r>) -> Self` ### Parameters #### Parameters - **registry** (`&Registry<'r>`) - Required - Prebuilt registry for dialect and `$ref` resolution. ### Request Example ```rust let options = jsonschema::canonical::options().with_registry(®istry); ``` ### Response #### Success Response - **Self** - The builder with the registry set. #### Response Example ```rust CanonicalizeOptions { /* with registry */ } ``` ``` -------------------------------- ### Access original exception from ValidationError Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-py/README.md Catch a `ValidationError` and inspect its `__cause__` to get the original exception raised by a custom keyword. ```python try: validator.validate(instance) except jsonschema_rs.ValidationError as e: print(type(e.__cause__)) # print(e.__cause__) # original message ``` -------------------------------- ### PreparedDocument<'a> Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/canonical.md Documentation for the PreparedDocument struct and its methods for canonicalizing JSON Schemas. ```APIDOC ## `PreparedDocument<'a>` ### Description Represents a prepared JSON Schema document, providing methods to canonicalize the document or subschemas and to find unsatisfiable subschemas. ### Methods #### `draft()` - **Returns**: `Draft` - **Description**: Returns the draft the document was read under. #### `canonicalize()` - **Returns**: `CanonicalSchema` - **Description**: Canonicalizes the whole document. #### `canonicalize_at(pointer)` - **Parameters**: - `pointer` (`&str`) - Required - A JSON Pointer to a subschema within the document's resolving context. - **Returns**: `CanonicalSchema` - **Description**: Canonicalizes the subschema at the given JSON Pointer. Errors: `CanonicalizationError::PointerNotFound` for unknown pointers, `InvalidSchemaType` for non-schema targets. #### `unsatisfiable()` - **Returns**: `BTreeMap` - **Description**: Returns a map of subschema pointers that admit no value, each with the reason. A pointer absent from the map is not proven satisfiable. `UnsatisfiableReason` has variants `Literal`, `Empty(Cause)`, `Conflict(Vec)`; `Cause { pointer: String, keywords: Vec }`. ### Example ```rust let document = json!({ "$defs": { "Named": {"type": "object", "required": ["name"]}, "Pet": {"allOf": [ {"$ref": "#/$defs/Named"}, {"properties": {"age": {"type": "integer", "minimum": 0}}} ]} } }); let prepared = jsonschema::canonical::options().prepare(&document)?; let pet = prepared.canonicalize_at("/$defs/Pet")?; assert_eq!(pet.to_json_schema()["required"], json!(["name"])); # Ok::<(), Box>(()) ``` ``` -------------------------------- ### Using draft-specific modules: options, is_valid, validate Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/drafts.md Shows how to use draft-specific modules: build a validator with custom format for draft202012, and use one-off helpers is_valid and validate for draft7 and draft6. The example uses the `?` operator, so it must be inside a function returning a Result. The `# Ok::<(), Box>(())` line is a hidden line that makes the example compile as a standalone test. ```rust use serde_json::json; let schema = json!({"type": "string", "format": "ends-with-42"}); // Explicit draft + custom format let validator = jsonschema::draft202012::options() .with_format("ends-with-42", |s| s.ends_with("42")) .should_validate_formats(true) .build(&schema)?; assert!(validator.is_valid(&json!("Hello 42"))); assert!(!validator.is_valid(&json!("No!"))); // One-off helpers assert!(jsonschema::draft7::is_valid(&json!({"minimum": 5}), &json!(42))); assert!(jsonschema::draft6::validate(&json!({"minimum": 5}), &json!(3)).is_err()); # Ok::<(), Box>(()) ``` -------------------------------- ### CLI usage: jsonschema-cli schema.json -i instance.json Source: https://github.com/stranger6667/jsonschema/blob/master/README.md Shows how to validate a JSON instance against a schema from the command line using the jsonschema-cli crate. ```console $ jsonschema-cli schema.json -i instance.json ``` -------------------------------- ### PreparedDocument struct and methods Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/canonical.md Shows the public API of `PreparedDocument<'a>`: the struct definition and its four methods. `draft()` returns the draft used, `canonicalize()` processes the whole document, `canonicalize_at(pointer)` processes a subschema at a JSON Pointer, and `unsatisfiable()` returns a map of subschema pointers that admit no value. ```rust pub struct PreparedDocument<'a> { /* document, draft, pattern_options, validate_formats, resolution, regexes, seed */ } #[must_use] pub fn draft(&self) -> Draft pub fn canonicalize(&self) -> Result pub fn canonicalize_at(&self, pointer: &str) -> Result pub fn unsatisfiable(&self) -> Result, CanonicalizationError> ``` -------------------------------- ### Using options_for with custom JSON type Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/lib.md Example of building a validator with a custom JSON representation using options_for. The schema is provided as a serde_json value. ```rust # type MyJson = jsonschema::json::SerdeJson; let validator = jsonschema::options_for::() .build(&serde_json::json!({"type": "string"})) .expect("valid schema"); ``` -------------------------------- ### Get collected annotations from evaluation Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-rb/README.md Returns annotations from nodes that passed. A failed node reports its annotations as droppedAnnotations in the list and hierarchical output instead. ```ruby valid_eval = validator.evaluate({ "name" => "Alice", "age" => 30 }) valid_eval.annotations # => [{schemaLocation: "/properties", absoluteKeywordLocation: nil, # instanceLocation: "", annotations: ["age", "name"]}] ``` -------------------------------- ### Canonicalize a schema and check satisfiability Source: https://github.com/stranger6667/jsonschema/blob/master/crates/jsonschema-py/README.md Shows how to canonicalize a schema with allOf, compare equivalent schemas, and detect an unsatisfiable schema. The canonical form includes the $schema keyword and the satisfiability() method returns Satisfiability.NO for schemas that accept no values. ```python import jsonschema_rs canonical = jsonschema_rs.canonicalize({ "allOf": [ {"type": "integer", "minimum": 0}, {"minimum": 10, "maximum": 100}, ] }) assert canonical.to_json_schema() == { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "integer", "minimum": 10, "maximum": 100, } # However they were written, equivalent schemas compare equal same = jsonschema_rs.canonicalize( {"type": "integer", "maximum": 100, "minimum": 10} ) assert canonical == same # A schema no value can satisfy collapses from jsonschema_rs.canonical import Satisfiability empty = jsonschema_rs.canonicalize( {"type": "integer", "minimum": 10, "maximum": 5} ) assert empty.satisfiability() == Satisfiability.NO ``` -------------------------------- ### Registry public methods Source: https://github.com/stranger6667/jsonschema/blob/master/_autodocs/api-reference/referencing.md Lists the public methods of Registry: new, contains_resource, resolver, find_vocabularies, and resolve_uri. ```rust #[must_use] pub fn new<'b>() -> RegistryBuilder<'b> pub fn contains_resource(&self, uri: &str) -> bool pub fn resolver(&self, base_uri: Uri) -> Resolver<'_> pub fn find_vocabularies(&self, draft: Draft, contents: &Value) -> VocabularySet pub fn resolve_uri(&self, base: &Uri<&str>, uri: &str) -> Result>, Error> ```