Grav v1.14.0

JSON Schema

import "std/data" (included in import "std") · namespace std.data

Checking JSON against a JSON Schema (the Draft 2020-12 keywords APIs use, and OpenAPI 3.0's nullable), and making a schema from a class: the fields JsonMap reads.

grav
import "std"

class Line {
    @Schema(min: 1, max: 99) public qty: int = 1
    public sku: string = ""
    constructor() {}
}

class Order {
    public id: long = 0
    @Schema(format: "email") public email: string = ""
    public note: string? = null
    public lines: Array<Line> = new Array<Line>()
    constructor() {}
}

fn main() {
    let schema = JsonSchema.compile(JsonSchema.forClass(reflect(Order)))
    let body = Json.parse("{\"id\": 7, \"email\": \"ada@\", \"lines\": [{\"qty\": 0, \"sku\": \"A1\"}, {\"qty\": 2}]}")
    for (e in schema.validate(body)) { print(e.toString()) }
    print(schema.isValid(Json.parse("{\"id\": 7, \"email\": \"ada@acme.test\", \"lines\": []}")))

    let s = JsonSchema.parse("{\"type\": \"array\", \"items\": {\"enum\": [\"red\", \"green\"]}, \"uniqueItems\": true}")
    for (e in s.validate(Json.parse("[\"red\", \"blue\", \"red\"]"))) { print("${e.path} ${e.keyword}: ${e.message}") }
}
Output
/email: must be a valid email
/lines/0/qty: must be at least 1
/lines/1/sku: is required
true
/1 enum: must be one of ["red","green"]
/2 uniqueItems: repeats item 0
  • Checked keywords. type, enum, const; minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf; minLength, maxLength, pattern, format (email, uri, date, date-time, time, uuid, ipv4, ipv6, hostname); properties, required, additionalProperties, patternProperties, propertyNames, minProperties, maxProperties, dependentRequired; items, prefixItems, minItems, maxItems, uniqueItems, contains; allOf, anyOf, oneOf, not, if/then/else; $ref to anywhere in the same document (#/$defs/…), recursion included; and nullable. Annotations (title, description, examples, …) are left alone, as are unknown formats. Patterns are ECMAScript-style: \d, \w, \s work.
  • Errors (JsonSchemaError) give a JSON Pointer path to the value, a message, and the keyword; at most maxErrors (100) are collected.
  • From a class. JsonSchema.forClass(reflect(T)) describes the fields JsonMap maps: their keys (@JsonName, @JsonSnakeCase), types, and nested classes under $defs. Fields whose type is not T? are required. @Schema(...) on a field adds keywords to its property (min and max are minimum and maximum; format, pattern, minLength, description, example, … as named).
  • Speed. compile reads each keyword once into a tree of nodes (patterns compiled, $refs resolved once), so checking an order of five fields and three lines takes about 8 µs.

API

class JsonSchemaError

One way a value does not fit: where (a JSON Pointer, "" for the whole value), why, and the keyword that said so.

Constructors

  • new JsonSchemaError(path: string, message: string, keyword: string)

Fields

  • path: string
  • message: string
  • keyword: string

Methods

  • fn toString() -> string

class SchemaNode

A schema compiled for checking: each keyword read once into a field.

Constructors

  • new SchemaNode(raw: JsonValue)

Fields

  • raw: JsonValue
  • fixed: int = -1 — -1 an object schema, 0 the schema false, 1 the schema true.
  • ref: string = ""
  • refNode: SchemaNode = null
  • types: int = 0 // bits: 1 string, 2 integer, 4 number, 8 boolean, 16 object, 32 array, 64 null — bits: 1 string, 2 integer, 4 number, 8 boolean, 16 object, 32 array, 64 null
  • typeRaw: JsonValue = null
  • nullable: bool = false
  • constV: JsonValue = null
  • enumV: JsonValue = null
  • num: bool = false
  • hasMin: bool = false
  • min: double = 0.0
  • hasMax: bool = false
  • max: double = 0.0
  • hasExMin: bool = false
  • exMin: double = 0.0
  • hasExMax: bool = false
  • exMax: double = 0.0
  • exMinFlag: bool = false
  • exMaxFlag: bool = false
  • multipleOf: double = 0.0
  • str: bool = false
  • minLen: long = -1
  • maxLen: long = -1
  • pattern: Regex = null
  • patternText: string = ""
  • format: string = ""
  • obj: bool = false
  • required: Array<string> = null
  • props: HashMap<string, SchemaNode> = null
  • patternProps: Array<Regex> = null
  • patternNodes: Array<SchemaNode> = null
  • additional: SchemaNode = null
  • names: SchemaNode = null
  • minProps: long = -1
  • maxProps: long = -1
  • dependent: HashMap<string, Array<string>> = null
  • arr: bool = false
  • prefix: Array<SchemaNode> = null
  • items: SchemaNode = null
  • minItems: long = -1
  • maxItems: long = -1
  • unique: bool = false
  • contains: SchemaNode = null
  • minContains: long = 1
  • maxContains: long = -1
  • allOf: Array<SchemaNode> = null
  • anyOf: Array<SchemaNode> = null
  • oneOf: Array<SchemaNode> = null
  • notN: SchemaNode = null
  • ifN: SchemaNode = null
  • thenN: SchemaNode = null
  • elseN: SchemaNode = null

class JsonSchema

Constructors

  • new JsonSchema(root: JsonValue)

Static members

  • static fn compile(schema: JsonValue) -> JsonSchema — A schema to check values with (true and false are schemas too).
  • static fn parse(text: string) -> JsonSchema — compile, from JSON text.
  • static fn typeBit(t: string) -> int
  • static fn isType(t: string, v: JsonValue) -> bool
  • static fn kindWord(v: JsonValue) -> string
  • static fn posix(p: string) -> string — ECMAScript's \d, \w, \s (and \D, \W, \S) in POSIX terms.
  • static fn unpercent(s: string) -> string — %XX escapes decoded (a $ref is a URI fragment).
  • static fn escape(k: string) -> string — A key as a JSON Pointer part.
  • static fn forClass(cls: ClassInfo) -> JsonValue — The schema of what JsonMap reads into cls: its mapped fields as properties, those whose type is not T? required, nested classes in $defs. @Schema(...) on a field adds to its property: minimum, maximum, minLength, maxLength, pattern, format, description, example, … as named (min and max are minimum and maximum).

Fields

  • root: JsonValue
  • maxErrors: int = 100 — At most this many errors are collected.

Methods

  • fn validate(value: JsonValue) -> Array<JsonSchemaError> — Every way value does not fit (empty when it fits).
  • fn isValid(value: JsonValue) -> bool

class JsonFormats

The format keyword's checks.

Static members

  • static fn check(format: string, s: string) -> bool
  • static fn email(s: string) -> bool
  • static fn uri(s: string) -> bool
  • static fn date(s: string) -> bool
  • static fn time(s: string) -> bool — hh:mm:ss[.frac] with Z or ±hh:mm
  • static fn ipv4(s: string) -> bool
  • static fn ipv6(s: string) -> bool
  • static fn hostname(s: string) -> bool

Edit this page on GitHub