Data formats

JSON Schema

Check values against a JSON Schema (drafts 4 to 2020-12), with every error and the path of the value at fault.

Version 1.0.0 · 3 functions · 1 crate

#json#api#forms#validation

Functions

What use json_schema.qwer gives a program, with the types Quillo sees. To take only some, or under other names: use schema_errors, schema_valid from json_schema (Quillo 0.6).

schema_errors(value: any, schema: any) → listor an error

Every way value breaks schema: { path, message, schema_path } each, path a JSON Pointer to the value at fault (/items/2/price, "" for the whole value), schema_path the rule it broke. An empty list when it is valid. The draft is the schema's $schema, 2020-12 when it names none; $refs to other files or URLs are not fetched. At most 200 errors.

schema_valid(value: any, schema: any) → boolor an error

Whether value is valid against schema.

schema_problems(schema: any) → list

The problems of a schema itself (a misspelt type, a bad pattern): an empty list for a schema that can be used.

Get it

$ quillo install json_schema               # json_schema.qwer into this folder$ quillo install json_schema --example     # and its example, json_schema.qwe

Or with curl:

$ curl -O https://quillolang.org/plugins/files/json_schema.qwer$ curl -O https://quillolang.org/plugins/files/json_schema.qwe

Then, in your program, all of it or only what you call:

main.qwe
use json_schema.qweruse schema_errors, schema_valid from json_schema      // Quillo 0.6: only these

It uses this crate, which cargo fetches the first time the plugin is built:

[dependencies]
jsonschema = { version = "0.26", default-features = false }

Example

json_schema.qwe
// An orders API that checks each body against a JSON Schema and says what is wrong, field by field.////   quillo run json_schema.qwe      then open http://localhost:8080/samplesuse "json_schema.qwer"let ORDER = {    "$schema": "https://json-schema.org/draft/2020-12/schema",    type: "object",    required: ["customer", "items"],    properties: {        customer: { type: "string", format: "email" },        items: {            type: "array", minItems: 1,            items: { type: "object", required: ["sku", "qty"], properties: { sku: { type: "string", pattern: "^[A-Z][0-9]+$" }, qty: { type: "integer", minimum: 1 } } },        },        note: { type: "string", maxLength: 200 },    },    additionalProperties: false,}route POST /orders {    let errors = schema_errors(request.json, ORDER)?    if len(errors) > 0 { reply 422 { errors } }    { accepted: request.json.customer }}route GET /samples = {    good: schema_valid({ customer: "ada@example.com", items: [{ sku: "B7", qty: 2 }] }, ORDER)?,    bad: schema_errors({ customer: "ada@example.com", items: [{ sku: "b7", qty: 0 }, { qty: 1 }], colour: "red" }, ORDER)? | map((e) => `${e.path}: ${e.message}`),    broken_schema: schema_problems({ type: "strnig" }),}
$ quillo run json_schema.qwe$ curl 'localhost:8080/samples'

Source

json_schema.qwer
//! Check values against a JSON Schema (drafts 4 to 2020-12): every error with the path of the value at fault, for API bodies, imports and config files.//! version: 1.0.0//!//! [dependencies]//! jsonschema = { version = "0.26", default-features = false }use serde_json::{json, Value};fn validator(schema: &Value) -> Result<jsonschema::Validator, String> {    jsonschema::validator_for(schema).map_err(|e| format!("the schema is not valid: {} (at {})", e, e.instance_path))}/// Every way `value` breaks `schema`: `{ path, message, schema_path }` each, `path` a JSON Pointer to the value at fault (`/items/2/price`,/// `""` for the whole value), `schema_path` the rule it broke. An empty list when it is valid. The draft is the schema's/// `$schema`, 2020-12 when it names none; `$ref`s to other files or URLs are not fetched. At most 200 errors.pub fn schema_errors(value: serde_json::Value, schema: serde_json::Value) -> Result<Vec<Value>, String> {    let v = validator(&schema)?;    Ok(v.iter_errors(&value).take(200).map(|e| json!({        "path": e.instance_path.to_string(),        "message": e.to_string(),        "schema_path": e.schema_path.to_string(),    })).collect())}/// Whether `value` is valid against `schema`.pub fn schema_valid(value: serde_json::Value, schema: serde_json::Value) -> Result<bool, String> {    Ok(validator(&schema)?.is_valid(&value))}/// The problems of a schema itself (a misspelt type, a bad pattern): an empty list for a schema that can be used.pub fn schema_problems(schema: serde_json::Value) -> Vec<String> {    match jsonschema::validator_for(&schema) {        Ok(_) => vec![],        Err(e) => vec![format!("{} (at {})", e, e.instance_path)],    }}
Thread
88Useful? Like it, or add to its thread below.

Thread 0 posts

On JSON Schema: questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.