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}") }
}/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;$refto anywhere in the same document (#/$defs/…), recursion included; andnullable. Annotations (title,description,examples, …) are left alone, as are unknown formats. Patterns are ECMAScript-style:\d,\w,\swork. - Errors (
JsonSchemaError) give a JSON Pointerpathto the value, amessage, and thekeyword; at mostmaxErrors(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 notT?are required.@Schema(...)on a field adds keywords to its property (minandmaxareminimumandmaximum;format,pattern,minLength,description,example, … as named). - Speed.
compilereads 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: stringmessage: stringkeyword: 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: JsonValuefixed: int = -1— -1 an object schema, 0 the schema false, 1 the schema true.ref: string = ""refNode: SchemaNode = nulltypes: 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 nulltypeRaw: JsonValue = nullnullable: bool = falseconstV: JsonValue = nullenumV: JsonValue = nullnum: bool = falsehasMin: bool = falsemin: double = 0.0hasMax: bool = falsemax: double = 0.0hasExMin: bool = falseexMin: double = 0.0hasExMax: bool = falseexMax: double = 0.0exMinFlag: bool = falseexMaxFlag: bool = falsemultipleOf: double = 0.0str: bool = falseminLen: long = -1maxLen: long = -1pattern: Regex = nullpatternText: string = ""format: string = ""obj: bool = falserequired: Array<string> = nullprops: HashMap<string, SchemaNode> = nullpatternProps: Array<Regex> = nullpatternNodes: Array<SchemaNode> = nulladditional: SchemaNode = nullnames: SchemaNode = nullminProps: long = -1maxProps: long = -1dependent: HashMap<string, Array<string>> = nullarr: bool = falseprefix: Array<SchemaNode> = nullitems: SchemaNode = nullminItems: long = -1maxItems: long = -1unique: bool = falsecontains: SchemaNode = nullminContains: long = 1maxContains: long = -1allOf: Array<SchemaNode> = nullanyOf: Array<SchemaNode> = nulloneOf: Array<SchemaNode> = nullnotN: SchemaNode = nullifN: SchemaNode = nullthenN: SchemaNode = nullelseN: 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) -> intstatic fn isType(t: string, v: JsonValue) -> boolstatic fn kindWord(v: JsonValue) -> stringstatic 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 intocls: its mapped fields as properties, those whose type is notT?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: JsonValuemaxErrors: int = 100— At most this many errors are collected.
Methods
fn validate(value: JsonValue) -> Array<JsonSchemaError>— Every wayvaluedoes 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) -> boolstatic fn email(s: string) -> boolstatic fn uri(s: string) -> boolstatic fn date(s: string) -> boolstatic fn time(s: string) -> bool— hh:mm:ss[.frac] with Z or ±hh:mmstatic fn ipv4(s: string) -> boolstatic fn ipv6(s: string) -> boolstatic fn hostname(s: string) -> bool