Programming Search⌘K

Taskcore

Validate data against a schema

Also called validate JSON, JSON Schema validation, check data against a schema, schema validation, validate XML against a schema.

Check a JSON value against the core keywords of JSON Schema 2020-12 and list each failed assertion with its instance location and keyword location as JSON Pointers.

Task

Check a JSON value against a JSON Schema, and report each part of the value that breaks a rule.

Each solution is a function validate(schema, instance). Both arguments are JSON texts. The result is a list of pairs, one for each assertion that fails. The first element of a pair is the instance location, a JSON Pointer to the value that failed. The second element is the keyword location, a JSON Pointer to the keyword in the schema. The output units of JSON Schema 2020-12 have these two fields, with the names instanceLocation and keywordLocation1. An empty list means that the instance is valid.

The solutions apply nine keywords of JSON Schema 2020-1212:

  • type accepts a value of one of the given types: null, boolean, object, array, number, string or integer. The type integer "matches any number with a zero fractional part"2, so 1.0 is an integer.
  • minimum and maximum are inclusive limits for a number.
  • minLength and maxLength are inclusive limits for the length of a string. The length is "the number of its characters as defined by RFC 8259"2, that is, the number of code points.
  • required gives the names that an object must have.
  • properties gives a schema for the member of each name, if the member exists.
  • additionalProperties gives a schema for each member that properties does not name.
  • items gives a schema for each element of an array.

The schema true accepts every value, and the schema false accepts no value1. A keyword that tests one type applies only to a value of that type, so {"minimum": 5} accepts the string "abc". The solutions ignore all other keywords. The core specification says: "Implementations SHOULD treat keywords they do not support as annotations"1.

For the schema and the instance

{"type": "object", "required": ["name", "age"],
 "properties": {"name": {"type": "string", "minLength": 1}, "age": {"type": "integer", "minimum": 0}}}
{"name": "", "age": 3.5}

the result is [["/age", "/properties/age/type"], ["/name", "/properties/name/minLength"]].

The pairs are sorted by the instance location and then by the keyword location, in code point order. Thus each language gives the same list. In a JSON Pointer, "'~' needs to be encoded as '~0' and '/' needs to be encoded as '~1'"3. The solution reports invalid-json when the schema or the instance is not a JSON text.

The contract limits the input in three ways. Each number has at most 15 significant digits. A decimal number with at most 15 significant digits goes to a double and back with no change4, so the comparisons give the same result in each language. Each name holds only characters below U+D800, so UTF-16 order and code point order agree. The schema has no keyword that starts with a dollar sign, such as $ref, because a reference needs the URI rules of the core specification.

Solutions

The standard libraries of the tier-1 languages have no JSON Schema validator. Each solution parses the two texts with the JSON parser of its standard library. Then a recursive function walks the schema and the instance together and carries the two locations. Each failed assertion adds a pair to a list, and the list is sorted at the end. In real code, use a library that implements the full specification, such as jsonschema for Python5 or Ajv for JavaScript6. The page JSON Schema describes the format and its versions. The file matrix.yaml records the verdicts for the other languages.

  • Python. json.loads makes true a bool, and bool is a subclass of int. Thus the solution tests for bool before int. A float is an integer when is_integer() returns True. len counts the code points of a string.
  • JavaScript and TypeScript (Node.js). typeof null and typeof [] both give "object", so the solution tests for null and Array.isArray first. Number.isInteger tests for a zero fractional part. The length of a string is its length "in UTF-16 code units"7, so the solution counts the code points with the spread syntax [...value]. It uses Object.hasOwn for each name, because the operator in also finds inherited names such as toString.
  • C#. JsonDocument.Parse gives a tree of JsonElement values, and ValueKind gives the type of each value. EnumerateRunes returns "an enumeration of Rune from this string"8, one for each code point, and the solution counts them. string.CompareOrdinal sorts by UTF-16 code units, which agrees with code point order under the contract.
  • Go. json.Unmarshal into an any stores a bool, a float64, a string, a []any, a map[string]any or nil9, and a type switch selects the keywords for each. len counts the bytes of a string, and utf8.RuneCountInString counts its runes10. "The iteration order over maps is not specified"11, so the members come in a different order on each run, and the sort makes the result stable.

An XML document has its own schema languages, such as XML Schema (XSD). In .NET, XmlReaderSettings with ValidationType.Schema makes an XmlReader validate the document while it reads it, and a ValidationEventHandler gets each error12. Here the age is negative, and the element role is not in the schema:

using System.Xml;
using System.Xml.Schema;

string xsd = """
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="user">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="age" type="xs:nonNegativeInteger"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
    """;
string xml = """
    <user>
      <name>Ada</name>
      <age>-1</age>
      <role>admin</role>
    </user>
    """;
var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema };
settings.Schemas.Add(null, XmlReader.Create(new StringReader(xsd)));
settings.ValidationEventHandler += (sender, e) =>
    Console.WriteLine($"{e.Severity} at line {e.Exception.LineNumber}: {e.Message}");
using (XmlReader reader = XmlReader.Create(new StringReader(xml), settings))
{
    while (reader.Read()) { }
}
Output
Error at line 3: The 'age' element is invalid - The value '-1' is invalid according to its datatype 'http://www.w3.org/2001/XMLSchema:nonNegativeInteger' - Value '-1' was either too large or too small for NonNegativeInteger.
Error at line 4: The element 'user' has invalid child element 'role'.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case gives the schema, the instance and the sorted pairs.

  • integer-from-fraction-zero, integer-from-exponent and integer-with-fraction: 1.0 and 1e2 are integers, and 3.5 is not.
  • boolean-not-integer and boolean-not-number: true and false are booleans, not numbers.
  • null-not-object and array-not-object: null and [] are not objects.
  • type-list-match and type-list-miss: {"type": ["string", "null"]} accepts null and rejects 5.
  • max-length-astral, min-length-astral and combining-mark: the emoji U+1F600 has the length 1, also when the text writes it as two escapes. The letter e and the combining acute accent U+0301 have the length 2.
  • other-type-keywords and other-type-keywords-number: the keywords for numbers, objects and arrays do not apply to a string, and the keywords for strings and objects do not apply to a number.
  • unknown-keyword and format-is-annotation: {"minimun": 5} accepts 1, and {"format": "email"} accepts any string.
  • true-schema, false-schema, empty-schema and false-member-schema: the schema false fails at its own location, which is the empty pointer at the root.
  • pointer-escape and pointer-escape-order: the names a/b, m~n and ~1 become a~1b, m~0n and ~01 in the pointers.
  • absent-property, required-all-missing and required-null-member: a missing member is not an error for properties. Three missing names give one error for required. A member with the value null exists.
  • inclusive-bounds, negative-zero and fraction-minimum: 0 and 10 pass the limits 0 and 10, and -0 passes the minimum 0.
  • index-order and keyword-order: the pointer /10 sorts before /2, and /minimum sorts before /type.
  • inherited-name and proto-member: the names toString, constructor and __proto__ are normal names.
  • non-ascii-name, nested-items and deep-path: names outside ASCII, an array of arrays, and pointers of five steps.

The cases in cases/errors.jsonl are failures. The toolchain does not load this file yet, so the test files hold these cases by name. A trailing comma, NaN, an empty text, a text with no end and single quotes are not JSON, so each gives invalid-json.

Pitfalls

  • A property in properties is optional. The OWASP Input Validation Cheat Sheet says that "listing a property alone neither requires it nor rejects unknown fields"13. Name each member that must exist in required. To reject other members, set additionalProperties to false. The cases absent-property and no-additional show both rules.

  • A misspelled keyword is not an error. A validator ignores a keyword that it does not know1, so {"minimun": 5} accepts every value. Test each schema with an instance that must fail.

  • format does not validate by default. In JSON Schema 2020-12, the value of format is an annotation unless the schema asks for the Format-Assertion vocabulary2. The jsonschema library for Python says that, with no format checker, "no format validation is done"5. Give a format checker to the validator, or check the format in the program.

  • A Python bool is an int. A check for integer with isinstance accepts true and rejects 1.0:

This code runs but gives a wrong answer on purpose.

import json

for text in ["true", "1", "1.0", "1.5"]:
    value = json.loads(text)
    print(text, type(value).__name__, isinstance(value, int))
Output
true bool True
1 int True
1.0 float False
1.5 float False

Test for bool first, and accept a float when is_integer() returns True.

  • JavaScript types and lengths differ from JSON Schema. length counts UTF-16 code units, typeof gives "object" for null and for an array, and in finds inherited names:
const s = "\u{1F600}";
console.log(s.length, [...s].length);
console.log(typeof null, typeof [], Array.isArray([]));
const value = JSON.parse("{}");
console.log("toString" in value, Object.hasOwn(value, "toString"));
Output
2 1
object object true
true false
  • Validate the data where it enters the program. OWASP says: "Reject invalid requests with a clear error; do not continue with partially validated data"13. Validation after parsing does not protect the parser: "A schema check after parsing cannot protect a parser that has already exhausted resources"13. Limit the size of the input before you parse it.

Code

The build runs the native tests of each language in a pinned toolchain.

validate.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/validate-data-against-a-schema/.

import json


def _reject(name):
    raise ValueError(f"{name} is not valid JSON")


def _pointer(name):
    # RFC 6901: "~" becomes "~0" first, then "/" becomes "~1".
    return "/" + name.replace("~", "~0").replace("/", "~1")


def _type_of(value):
    # bool is a subclass of int, so it is tested first.
    if value is None:
        return {"null"}
    if isinstance(value, bool):
        return {"boolean"}
    if isinstance(value, int):
        return {"integer", "number"}
    if isinstance(value, float):
        return {"integer", "number"} if value.is_integer() else {"number"}
    if isinstance(value, str):
        return {"string"}
    if isinstance(value, list):
        return {"array"}
    return {"object"}


def _check(schema, value, here, at, errors):
    if schema is True:
        return
    if schema is False:
        errors.append((here, at))
        return
    kinds = _type_of(value)
    if "type" in schema:
        allowed = schema["type"]
        if isinstance(allowed, str):
            allowed = [allowed]
        if not kinds.intersection(allowed):
            errors.append((here, at + "/type"))
    if "number" in kinds:
        if "minimum" in schema and value < schema["minimum"]:
            errors.append((here, at + "/minimum"))
        if "maximum" in schema and value > schema["maximum"]:
            errors.append((here, at + "/maximum"))
    if "string" in kinds:
        # len counts code points, as RFC 8259 counts characters.
        if "minLength" in schema and len(value) < schema["minLength"]:
            errors.append((here, at + "/minLength"))
        if "maxLength" in schema and len(value) > schema["maxLength"]:
            errors.append((here, at + "/maxLength"))
    if "object" in kinds:
        if any(name not in value for name in schema.get("required", [])):
            errors.append((here, at + "/required"))
        named = schema.get("properties", {})
        for name, member in value.items():
            if name in named:
                _check(named[name], member, here + _pointer(name), at + "/properties" + _pointer(name), errors)
            elif "additionalProperties" in schema:
                _check(schema["additionalProperties"], member, here + _pointer(name), at + "/additionalProperties", errors)
    if "array" in kinds and "items" in schema:
        for index, item in enumerate(value):
            _check(schema["items"], item, f"{here}/{index}", at + "/items", errors)


def validate(schema, instance):
    """Return the sorted (instance location, keyword location) pairs of the failed assertions."""
    errors = []
    _check(json.loads(schema, parse_constant=_reject), json.loads(instance, parse_constant=_reject), "", "", errors)
    return sorted(errors)
test_validate.py 76 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/validate-data-against-a-schema/.

import pytest

from validate import validate

# name: (schema, instance, the failed (instance location, keyword location) pairs)
CASES = {
    "valid-object": ("{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": 36}", []),
    "missing-required": ("{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\"}", [("", "/required")]),
    "wrong-member-type": ("{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": \"36\"}", [("/age", "/properties/age/type")]),
    "below-minimum": ("{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": -1}", [("/age", "/properties/age/minimum")]),
    "two-errors": ("{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"\", \"age\": 3.5}", [("/age", "/properties/age/type"), ("/name", "/properties/name/minLength")]),
    "array-items": ("{\"type\": \"array\", \"items\": {\"type\": \"string\"}}", "[\"a\", 1, \"c\", null]", [("/1", "/items/type"), ("/3", "/items/type")]),
    "no-additional": ("{\"properties\": {\"id\": {\"type\": \"integer\"}}, \"additionalProperties\": false}", "{\"id\": 1, \"admin\": true}", [("/admin", "/additionalProperties")]),
    "integer-from-fraction-zero": ("{\"type\": \"integer\"}", "1.0", []),
    "integer-from-exponent": ("{\"type\": \"integer\"}", "1e2", []),
    "integer-with-fraction": ("{\"type\": \"integer\"}", "3.5", [("", "/type")]),
    "boolean-not-integer": ("{\"type\": \"integer\"}", "true", [("", "/type")]),
    "boolean-not-number": ("{\"type\": \"number\"}", "false", [("", "/type")]),
    "integer-is-number": ("{\"type\": \"number\"}", "3", []),
    "null-not-object": ("{\"type\": \"object\"}", "null", [("", "/type")]),
    "array-not-object": ("{\"type\": \"object\"}", "[]", [("", "/type")]),
    "type-list-match": ("{\"type\": [\"string\", \"null\"]}", "null", []),
    "type-list-miss": ("{\"type\": [\"string\", \"null\"]}", "5", [("", "/type")]),
    "max-length-astral": ("{\"maxLength\": 1}", "\"😀\"", []),
    "min-length-astral": ("{\"minLength\": 2}", "\"\\ud83d\\ude00\"", [("", "/minLength")]),
    "combining-mark": ("{\"maxLength\": 1}", "\"e\\u0301\"", [("", "/maxLength")]),
    "other-type-keywords": ("{\"minimum\": 5, \"required\": [\"a\"], \"items\": false}", "\"abc\"", []),
    "other-type-keywords-number": ("{\"maxLength\": 1, \"required\": [\"a\"], \"additionalProperties\": false}", "3", []),
    "unknown-keyword": ("{\"minimun\": 5}", "1", []),
    "format-is-annotation": ("{\"type\": \"string\", \"format\": \"email\"}", "\"not an email\"", []),
    "true-schema": ("true", "{\"a\": [1]}", []),
    "false-schema": ("false", "{}", [("", "")]),
    "empty-schema": ("{}", "null", []),
    "false-member-schema": ("{\"properties\": {\"a\": false}}", "{\"a\": 0, \"b\": 0}", [("/a", "/properties/a")]),
    "pointer-escape": ("{\"properties\": {\"a/b\": {\"type\": \"string\"}, \"m~n\": {\"type\": \"string\"}}}", "{\"a/b\": 1, \"m~n\": 2}", [("/a~1b", "/properties/a~1b/type"), ("/m~0n", "/properties/m~0n/type")]),
    "pointer-escape-order": ("{\"properties\": {\"~1\": false}}", "{\"~1\": 0}", [("/~01", "/properties/~01")]),
    "nested-items": ("{\"items\": {\"items\": {\"type\": \"integer\"}}}", "[[1, \"x\"], [2]]", [("/0/1", "/items/items/type")]),
    "additional-schema": ("{\"properties\": {\"id\": {}}, \"additionalProperties\": {\"type\": \"string\"}}", "{\"id\": 1, \"a\": \"x\", \"b\": 2}", [("/b", "/additionalProperties/type")]),
    "absent-property": ("{\"properties\": {\"a\": {\"type\": \"string\"}}}", "{}", []),
    "required-all-missing": ("{\"required\": [\"a\", \"b\", \"c\"]}", "{}", [("", "/required")]),
    "required-null-member": ("{\"required\": [\"a\"]}", "{\"a\": null}", []),
    "inclusive-bounds": ("{\"items\": {\"minimum\": 0, \"maximum\": 10}}", "[0, 10, 10.5, -0.5]", [("/2", "/items/maximum"), ("/3", "/items/minimum")]),
    "negative-zero": ("{\"minimum\": 0}", "-0", []),
    "fraction-minimum": ("{\"minimum\": 0.5}", "0.4", [("", "/minimum")]),
    "index-order": ("{\"items\": {\"type\": \"string\"}}", "[0, \"\", 0, \"\", \"\", \"\", \"\", \"\", \"\", \"\", 0]", [("/0", "/items/type"), ("/10", "/items/type"), ("/2", "/items/type")]),
    "keyword-order": ("{\"type\": \"string\", \"minimum\": 5}", "3", [("", "/minimum"), ("", "/type")]),
    "inherited-name": ("{\"required\": [\"toString\", \"constructor\"]}", "{}", [("", "/required")]),
    "proto-member": ("{\"properties\": {\"__proto__\": {\"type\": \"string\"}}}", "{\"__proto__\": 1}", [("/__proto__", "/properties/__proto__/type")]),
    "non-ascii-name": ("{\"required\": [\"é\"], \"properties\": {\"日本\": {\"type\": \"integer\"}}}", "{\"é\": 1, \"日本\": \"x\"}", [("/日本", "/properties/日本/type")]),
    "deep-path": ("{\"properties\": {\"a\": {\"items\": {\"properties\": {\"b\": {\"required\": [\"c\"]}}}}}}", "{\"a\": [{\"b\": {}}, {\"b\": {\"c\": 1}}, {\"b\": {}}]}", [("/a/0/b", "/properties/a/items/properties/b/required"), ("/a/2/b", "/properties/a/items/properties/b/required")]),
}

# name: (schema, instance); one of the texts is not JSON
INVALID = {
    "trailing-comma": ("{\"type\": \"array\"}", "[1, 2,]"),
    "nan": ("{\"type\": \"number\"}", "NaN"),
    "empty-instance": ("{}", ""),
    "bad-schema": ("{\"type\": ", "1"),
    "single-quotes": ("{}", "{'a': 1}"),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(name: str) -> None:
    schema, instance, want = CASES[name]
    assert validate(schema, instance) == want


@pytest.mark.parametrize("name", INVALID)
def test_invalid_json(name: str) -> None:
    schema, instance = INVALID[name]
    with pytest.raises(ValueError):
        validate(schema, instance)
SchemaValidator.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/validate-data-against-a-schema/.

using System.Text.Json;

public static class SchemaValidator
{
    // RFC 6901: "~" becomes "~0" first, then "/" becomes "~1".
    static string Pointer(string name) => "/" + name.Replace("~", "~0").Replace("/", "~1");

    static string[] Kinds(JsonElement value) => value.ValueKind switch
    {
        JsonValueKind.Null => ["null"],
        JsonValueKind.True or JsonValueKind.False => ["boolean"],
        JsonValueKind.Number => Math.Floor(value.GetDouble()) == value.GetDouble() ? ["integer", "number"] : ["number"],
        JsonValueKind.String => ["string"],
        JsonValueKind.Array => ["array"],
        _ => ["object"],
    };

    static void Check(JsonElement schema, JsonElement value, string here, string at, List<(string, string)> errors)
    {
        if (schema.ValueKind == JsonValueKind.True)
        {
            return;
        }
        if (schema.ValueKind == JsonValueKind.False)
        {
            errors.Add((here, at));
            return;
        }
        string[] kinds = Kinds(value);
        if (schema.TryGetProperty("type", out JsonElement type))
        {
            string?[] allowed = type.ValueKind == JsonValueKind.String
                ? [type.GetString()]
                : type.EnumerateArray().Select(t => t.GetString()).ToArray();
            if (!kinds.Any(allowed.Contains))
            {
                errors.Add((here, at + "/type"));
            }
        }
        switch (value.ValueKind)
        {
            case JsonValueKind.Number:
                double number = value.GetDouble();
                if (schema.TryGetProperty("minimum", out JsonElement minimum) && number < minimum.GetDouble())
                {
                    errors.Add((here, at + "/minimum"));
                }
                if (schema.TryGetProperty("maximum", out JsonElement maximum) && number > maximum.GetDouble())
                {
                    errors.Add((here, at + "/maximum"));
                }
                break;
            case JsonValueKind.String:
                // Length counts UTF-16 code units. EnumerateRunes counts code points.
                int length = value.GetString()!.EnumerateRunes().Count();
                if (schema.TryGetProperty("minLength", out JsonElement minLength) && length < minLength.GetDouble())
                {
                    errors.Add((here, at + "/minLength"));
                }
                if (schema.TryGetProperty("maxLength", out JsonElement maxLength) && length > maxLength.GetDouble())
                {
                    errors.Add((here, at + "/maxLength"));
                }
                break;
            case JsonValueKind.Object:
                if (schema.TryGetProperty("required", out JsonElement required)
                    && required.EnumerateArray().Any(name => !value.TryGetProperty(name.GetString()!, out _)))
                {
                    errors.Add((here, at + "/required"));
                }
                bool hasNamed = schema.TryGetProperty("properties", out JsonElement named);
                bool hasExtra = schema.TryGetProperty("additionalProperties", out JsonElement extra);
                foreach (JsonProperty member in value.EnumerateObject())
                {
                    if (hasNamed && named.TryGetProperty(member.Name, out JsonElement sub))
                    {
                        Check(sub, member.Value, here + Pointer(member.Name), at + "/properties" + Pointer(member.Name), errors);
                    }
                    else if (hasExtra)
                    {
                        Check(extra, member.Value, here + Pointer(member.Name), at + "/additionalProperties", errors);
                    }
                }
                break;
            case JsonValueKind.Array:
                if (schema.TryGetProperty("items", out JsonElement items))
                {
                    int index = 0;
                    foreach (JsonElement item in value.EnumerateArray())
                    {
                        Check(items, item, $"{here}/{index++}", at + "/items", errors);
                    }
                }
                break;
        }
    }

    // Returns the sorted (instance location, keyword location) pairs of the failed assertions.
    public static List<(string Instance, string Keyword)> Validate(string schema, string instance)
    {
        using JsonDocument s = JsonDocument.Parse(schema);
        using JsonDocument v = JsonDocument.Parse(instance);
        var errors = new List<(string, string)>();
        Check(s.RootElement, v.RootElement, "", "", errors);
        // CompareOrdinal compares UTF-16 code units, which is code point order for the names that the contract allows.
        errors.Sort((a, b) => string.CompareOrdinal(a.Item1, b.Item1) is int c && c != 0 ? c : string.CompareOrdinal(a.Item2, b.Item2));
        return errors;
    }
}
SchemaValidatorTests.cs 83 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/validate-data-against-a-schema/.

using System.Text.Json;
using Xunit;

public sealed class SchemaValidatorTests
{
    // case, schema, instance, the failed instance locations, and their keyword locations
    public static TheoryData<string, string, string, string[], string[]> Cases => new()
    {
        { "valid-object", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": 36}", [], [] },
        { "missing-required", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\"}", [""], ["/required"] },
        { "wrong-member-type", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": \"36\"}", ["/age"], ["/properties/age/type"] },
        { "below-minimum", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": -1}", ["/age"], ["/properties/age/minimum"] },
        { "two-errors", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"\", \"age\": 3.5}", ["/age", "/name"], ["/properties/age/type", "/properties/name/minLength"] },
        { "array-items", "{\"type\": \"array\", \"items\": {\"type\": \"string\"}}", "[\"a\", 1, \"c\", null]", ["/1", "/3"], ["/items/type", "/items/type"] },
        { "no-additional", "{\"properties\": {\"id\": {\"type\": \"integer\"}}, \"additionalProperties\": false}", "{\"id\": 1, \"admin\": true}", ["/admin"], ["/additionalProperties"] },
        { "integer-from-fraction-zero", "{\"type\": \"integer\"}", "1.0", [], [] },
        { "integer-from-exponent", "{\"type\": \"integer\"}", "1e2", [], [] },
        { "integer-with-fraction", "{\"type\": \"integer\"}", "3.5", [""], ["/type"] },
        { "boolean-not-integer", "{\"type\": \"integer\"}", "true", [""], ["/type"] },
        { "boolean-not-number", "{\"type\": \"number\"}", "false", [""], ["/type"] },
        { "integer-is-number", "{\"type\": \"number\"}", "3", [], [] },
        { "null-not-object", "{\"type\": \"object\"}", "null", [""], ["/type"] },
        { "array-not-object", "{\"type\": \"object\"}", "[]", [""], ["/type"] },
        { "type-list-match", "{\"type\": [\"string\", \"null\"]}", "null", [], [] },
        { "type-list-miss", "{\"type\": [\"string\", \"null\"]}", "5", [""], ["/type"] },
        { "max-length-astral", "{\"maxLength\": 1}", "\"😀\"", [], [] },
        { "min-length-astral", "{\"minLength\": 2}", "\"\\ud83d\\ude00\"", [""], ["/minLength"] },
        { "combining-mark", "{\"maxLength\": 1}", "\"e\\u0301\"", [""], ["/maxLength"] },
        { "other-type-keywords", "{\"minimum\": 5, \"required\": [\"a\"], \"items\": false}", "\"abc\"", [], [] },
        { "other-type-keywords-number", "{\"maxLength\": 1, \"required\": [\"a\"], \"additionalProperties\": false}", "3", [], [] },
        { "unknown-keyword", "{\"minimun\": 5}", "1", [], [] },
        { "format-is-annotation", "{\"type\": \"string\", \"format\": \"email\"}", "\"not an email\"", [], [] },
        { "true-schema", "true", "{\"a\": [1]}", [], [] },
        { "false-schema", "false", "{}", [""], [""] },
        { "empty-schema", "{}", "null", [], [] },
        { "false-member-schema", "{\"properties\": {\"a\": false}}", "{\"a\": 0, \"b\": 0}", ["/a"], ["/properties/a"] },
        { "pointer-escape", "{\"properties\": {\"a/b\": {\"type\": \"string\"}, \"m~n\": {\"type\": \"string\"}}}", "{\"a/b\": 1, \"m~n\": 2}", ["/a~1b", "/m~0n"], ["/properties/a~1b/type", "/properties/m~0n/type"] },
        { "pointer-escape-order", "{\"properties\": {\"~1\": false}}", "{\"~1\": 0}", ["/~01"], ["/properties/~01"] },
        { "nested-items", "{\"items\": {\"items\": {\"type\": \"integer\"}}}", "[[1, \"x\"], [2]]", ["/0/1"], ["/items/items/type"] },
        { "additional-schema", "{\"properties\": {\"id\": {}}, \"additionalProperties\": {\"type\": \"string\"}}", "{\"id\": 1, \"a\": \"x\", \"b\": 2}", ["/b"], ["/additionalProperties/type"] },
        { "absent-property", "{\"properties\": {\"a\": {\"type\": \"string\"}}}", "{}", [], [] },
        { "required-all-missing", "{\"required\": [\"a\", \"b\", \"c\"]}", "{}", [""], ["/required"] },
        { "required-null-member", "{\"required\": [\"a\"]}", "{\"a\": null}", [], [] },
        { "inclusive-bounds", "{\"items\": {\"minimum\": 0, \"maximum\": 10}}", "[0, 10, 10.5, -0.5]", ["/2", "/3"], ["/items/maximum", "/items/minimum"] },
        { "negative-zero", "{\"minimum\": 0}", "-0", [], [] },
        { "fraction-minimum", "{\"minimum\": 0.5}", "0.4", [""], ["/minimum"] },
        { "index-order", "{\"items\": {\"type\": \"string\"}}", "[0, \"\", 0, \"\", \"\", \"\", \"\", \"\", \"\", \"\", 0]", ["/0", "/10", "/2"], ["/items/type", "/items/type", "/items/type"] },
        { "keyword-order", "{\"type\": \"string\", \"minimum\": 5}", "3", ["", ""], ["/minimum", "/type"] },
        { "inherited-name", "{\"required\": [\"toString\", \"constructor\"]}", "{}", [""], ["/required"] },
        { "proto-member", "{\"properties\": {\"__proto__\": {\"type\": \"string\"}}}", "{\"__proto__\": 1}", ["/__proto__"], ["/properties/__proto__/type"] },
        { "non-ascii-name", "{\"required\": [\"é\"], \"properties\": {\"日本\": {\"type\": \"integer\"}}}", "{\"é\": 1, \"日本\": \"x\"}", ["/日本"], ["/properties/日本/type"] },
        { "deep-path", "{\"properties\": {\"a\": {\"items\": {\"properties\": {\"b\": {\"required\": [\"c\"]}}}}}}", "{\"a\": [{\"b\": {}}, {\"b\": {\"c\": 1}}, {\"b\": {}}]}", ["/a/0/b", "/a/2/b"], ["/properties/a/items/properties/b/required", "/properties/a/items/properties/b/required"] },
    };

    // case, schema, instance; one of the texts is not JSON
    public static TheoryData<string, string, string> Invalid => new()
    {
        { "trailing-comma", "{\"type\": \"array\"}", "[1, 2,]" },
        { "nan", "{\"type\": \"number\"}", "NaN" },
        { "empty-instance", "{}", "" },
        { "bad-schema", "{\"type\": ", "1" },
        { "single-quotes", "{}", "{'a': 1}" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void ReportsFailures(string name, string schema, string instance, string[] instances, string[] keywords)
    {
        var want = instances.Zip(keywords).ToList();
        Assert.True(want.SequenceEqual(SchemaValidator.Validate(schema, instance)), name);
    }

    [Theory]
    [MemberData(nameof(Invalid))]
    public void RejectsInvalidJson(string name, string schema, string instance)
    {
        Assert.ThrowsAny<JsonException>(() => SchemaValidator.Validate(schema, instance));
        Assert.NotNull(name);
    }
}
validate.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/validate-data-against-a-schema/.

// RFC 6901: "~" becomes "~0" first, then "/" becomes "~1".
const pointer = (name) => "/" + name.replaceAll("~", "~0").replaceAll("/", "~1");

function typeOf(value) {
  // typeof null is "object", so null is tested first.
  if (value === null) return ["null"];
  if (Array.isArray(value)) return ["array"];
  if (typeof value === "number") return Number.isInteger(value) ? ["integer", "number"] : ["number"];
  return [typeof value];
}

function check(schema, value, here, at, errors) {
  if (schema === true) return;
  if (schema === false) {
    errors.push([here, at]);
    return;
  }
  const has = (name) => Object.hasOwn(schema, name);
  const kinds = typeOf(value);
  if (has("type")) {
    const allowed = [schema.type].flat();
    if (!kinds.some((kind) => allowed.includes(kind))) errors.push([here, at + "/type"]);
  }
  if (kinds.includes("number")) {
    if (has("minimum") && value < schema.minimum) errors.push([here, at + "/minimum"]);
    if (has("maximum") && value > schema.maximum) errors.push([here, at + "/maximum"]);
  }
  if (kinds.includes("string")) {
    // value.length counts UTF-16 code units. The spread counts code points.
    const length = [...value].length;
    if (has("minLength") && length < schema.minLength) errors.push([here, at + "/minLength"]);
    if (has("maxLength") && length > schema.maxLength) errors.push([here, at + "/maxLength"]);
  }
  if (kinds.includes("object")) {
    // Object.hasOwn ignores the names that every object inherits, such as toString.
    if (has("required") && schema.required.some((name) => !Object.hasOwn(value, name))) {
      errors.push([here, at + "/required"]);
    }
    const named = has("properties") ? schema.properties : {};
    for (const [name, member] of Object.entries(value)) {
      if (Object.hasOwn(named, name)) {
        check(named[name], member, here + pointer(name), at + "/properties" + pointer(name), errors);
      } else if (has("additionalProperties")) {
        check(schema.additionalProperties, member, here + pointer(name), at + "/additionalProperties", errors);
      }
    }
  }
  if (kinds.includes("array") && has("items")) {
    value.forEach((item, index) => check(schema.items, item, `${here}/${index}`, at + "/items", errors));
  }
}

const order = (a, b) => (a < b ? -1 : a > b ? 1 : 0);

// Returns the sorted [instance location, keyword location] pairs of the failed assertions.
export function validate(schema, instance) {
  const errors = [];
  check(JSON.parse(schema), JSON.parse(instance), "", "", errors);
  return errors.sort((a, b) => order(a[0], b[0]) || order(a[1], b[1]));
}
validate.test.js 72 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/validate-data-against-a-schema/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { validate } from "./validate.js";

// [case, schema, instance, the failed [instance location, keyword location] pairs]
const cases = [
  ["valid-object", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": 36}", []],
  ["missing-required", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\"}", [["", "/required"]]],
  ["wrong-member-type", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": \"36\"}", [["/age", "/properties/age/type"]]],
  ["below-minimum", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": -1}", [["/age", "/properties/age/minimum"]]],
  ["two-errors", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"\", \"age\": 3.5}", [["/age", "/properties/age/type"], ["/name", "/properties/name/minLength"]]],
  ["array-items", "{\"type\": \"array\", \"items\": {\"type\": \"string\"}}", "[\"a\", 1, \"c\", null]", [["/1", "/items/type"], ["/3", "/items/type"]]],
  ["no-additional", "{\"properties\": {\"id\": {\"type\": \"integer\"}}, \"additionalProperties\": false}", "{\"id\": 1, \"admin\": true}", [["/admin", "/additionalProperties"]]],
  ["integer-from-fraction-zero", "{\"type\": \"integer\"}", "1.0", []],
  ["integer-from-exponent", "{\"type\": \"integer\"}", "1e2", []],
  ["integer-with-fraction", "{\"type\": \"integer\"}", "3.5", [["", "/type"]]],
  ["boolean-not-integer", "{\"type\": \"integer\"}", "true", [["", "/type"]]],
  ["boolean-not-number", "{\"type\": \"number\"}", "false", [["", "/type"]]],
  ["integer-is-number", "{\"type\": \"number\"}", "3", []],
  ["null-not-object", "{\"type\": \"object\"}", "null", [["", "/type"]]],
  ["array-not-object", "{\"type\": \"object\"}", "[]", [["", "/type"]]],
  ["type-list-match", "{\"type\": [\"string\", \"null\"]}", "null", []],
  ["type-list-miss", "{\"type\": [\"string\", \"null\"]}", "5", [["", "/type"]]],
  ["max-length-astral", "{\"maxLength\": 1}", "\"😀\"", []],
  ["min-length-astral", "{\"minLength\": 2}", "\"\\ud83d\\ude00\"", [["", "/minLength"]]],
  ["combining-mark", "{\"maxLength\": 1}", "\"e\\u0301\"", [["", "/maxLength"]]],
  ["other-type-keywords", "{\"minimum\": 5, \"required\": [\"a\"], \"items\": false}", "\"abc\"", []],
  ["other-type-keywords-number", "{\"maxLength\": 1, \"required\": [\"a\"], \"additionalProperties\": false}", "3", []],
  ["unknown-keyword", "{\"minimun\": 5}", "1", []],
  ["format-is-annotation", "{\"type\": \"string\", \"format\": \"email\"}", "\"not an email\"", []],
  ["true-schema", "true", "{\"a\": [1]}", []],
  ["false-schema", "false", "{}", [["", ""]]],
  ["empty-schema", "{}", "null", []],
  ["false-member-schema", "{\"properties\": {\"a\": false}}", "{\"a\": 0, \"b\": 0}", [["/a", "/properties/a"]]],
  ["pointer-escape", "{\"properties\": {\"a/b\": {\"type\": \"string\"}, \"m~n\": {\"type\": \"string\"}}}", "{\"a/b\": 1, \"m~n\": 2}", [["/a~1b", "/properties/a~1b/type"], ["/m~0n", "/properties/m~0n/type"]]],
  ["pointer-escape-order", "{\"properties\": {\"~1\": false}}", "{\"~1\": 0}", [["/~01", "/properties/~01"]]],
  ["nested-items", "{\"items\": {\"items\": {\"type\": \"integer\"}}}", "[[1, \"x\"], [2]]", [["/0/1", "/items/items/type"]]],
  ["additional-schema", "{\"properties\": {\"id\": {}}, \"additionalProperties\": {\"type\": \"string\"}}", "{\"id\": 1, \"a\": \"x\", \"b\": 2}", [["/b", "/additionalProperties/type"]]],
  ["absent-property", "{\"properties\": {\"a\": {\"type\": \"string\"}}}", "{}", []],
  ["required-all-missing", "{\"required\": [\"a\", \"b\", \"c\"]}", "{}", [["", "/required"]]],
  ["required-null-member", "{\"required\": [\"a\"]}", "{\"a\": null}", []],
  ["inclusive-bounds", "{\"items\": {\"minimum\": 0, \"maximum\": 10}}", "[0, 10, 10.5, -0.5]", [["/2", "/items/maximum"], ["/3", "/items/minimum"]]],
  ["negative-zero", "{\"minimum\": 0}", "-0", []],
  ["fraction-minimum", "{\"minimum\": 0.5}", "0.4", [["", "/minimum"]]],
  ["index-order", "{\"items\": {\"type\": \"string\"}}", "[0, \"\", 0, \"\", \"\", \"\", \"\", \"\", \"\", \"\", 0]", [["/0", "/items/type"], ["/10", "/items/type"], ["/2", "/items/type"]]],
  ["keyword-order", "{\"type\": \"string\", \"minimum\": 5}", "3", [["", "/minimum"], ["", "/type"]]],
  ["inherited-name", "{\"required\": [\"toString\", \"constructor\"]}", "{}", [["", "/required"]]],
  ["proto-member", "{\"properties\": {\"__proto__\": {\"type\": \"string\"}}}", "{\"__proto__\": 1}", [["/__proto__", "/properties/__proto__/type"]]],
  ["non-ascii-name", "{\"required\": [\"é\"], \"properties\": {\"日本\": {\"type\": \"integer\"}}}", "{\"é\": 1, \"日本\": \"x\"}", [["/日本", "/properties/日本/type"]]],
  ["deep-path", "{\"properties\": {\"a\": {\"items\": {\"properties\": {\"b\": {\"required\": [\"c\"]}}}}}}", "{\"a\": [{\"b\": {}}, {\"b\": {\"c\": 1}}, {\"b\": {}}]}", [["/a/0/b", "/properties/a/items/properties/b/required"], ["/a/2/b", "/properties/a/items/properties/b/required"]]],
];

// [case, schema, instance]; one of the texts is not JSON
const invalid = [
  ["trailing-comma", "{\"type\": \"array\"}", "[1, 2,]"],
  ["nan", "{\"type\": \"number\"}", "NaN"],
  ["empty-instance", "{}", ""],
  ["bad-schema", "{\"type\": ", "1"],
  ["single-quotes", "{}", "{'a': 1}"],
];

for (const [name, schema, instance, want] of cases) {
  test(name, () => assert.deepEqual(validate(schema, instance), want));
}

for (const [name, schema, instance] of invalid) {
  test(name, () => assert.throws(() => validate(schema, instance), SyntaxError));
}
validate.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/validate-data-against-a-schema/.

type Json = null | boolean | number | string | Json[] | { [name: string]: Json };
type Schema = boolean | { [keyword: string]: Json };
export type Failure = [instanceLocation: string, keywordLocation: string];

// RFC 6901: "~" becomes "~0" first, then "/" becomes "~1".
const pointer = (name: string): string => "/" + name.replaceAll("~", "~0").replaceAll("/", "~1");

function typeOf(value: Json): string[] {
  // typeof null is "object", so null is tested first.
  if (value === null) return ["null"];
  if (Array.isArray(value)) return ["array"];
  if (typeof value === "number") return Number.isInteger(value) ? ["integer", "number"] : ["number"];
  return [typeof value];
}

function check(schema: Schema, value: Json, here: string, at: string, errors: Failure[]): void {
  if (schema === true) return;
  if (schema === false) {
    errors.push([here, at]);
    return;
  }
  const has = (name: string): boolean => Object.hasOwn(schema, name);
  const kinds = typeOf(value);
  if (has("type")) {
    const allowed = [schema.type].flat();
    if (!kinds.some((kind) => allowed.includes(kind))) errors.push([here, at + "/type"]);
  }
  if (typeof value === "number") {
    if (has("minimum") && value < (schema.minimum as number)) errors.push([here, at + "/minimum"]);
    if (has("maximum") && value > (schema.maximum as number)) errors.push([here, at + "/maximum"]);
  }
  if (typeof value === "string") {
    // value.length counts UTF-16 code units. The spread counts code points.
    const length = [...value].length;
    if (has("minLength") && length < (schema.minLength as number)) errors.push([here, at + "/minLength"]);
    if (has("maxLength") && length > (schema.maxLength as number)) errors.push([here, at + "/maxLength"]);
  }
  if (value !== null && typeof value === "object" && !Array.isArray(value)) {
    // Object.hasOwn ignores the names that every object inherits, such as toString.
    const required = has("required") ? (schema.required as string[]) : [];
    if (required.some((name) => !Object.hasOwn(value, name))) errors.push([here, at + "/required"]);
    const named = (has("properties") ? schema.properties : {}) as { [name: string]: Schema };
    for (const [name, member] of Object.entries(value)) {
      if (Object.hasOwn(named, name)) {
        check(named[name], member, here + pointer(name), at + "/properties" + pointer(name), errors);
      } else if (has("additionalProperties")) {
        check(schema.additionalProperties as Schema, member, here + pointer(name), at + "/additionalProperties", errors);
      }
    }
  }
  if (Array.isArray(value) && has("items")) {
    value.forEach((item, index) => check(schema.items as Schema, item, `${here}/${index}`, at + "/items", errors));
  }
}

const order = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);

// Returns the sorted [instance location, keyword location] pairs of the failed assertions.
export function validate(schema: string, instance: string): Failure[] {
  const errors: Failure[] = [];
  check(JSON.parse(schema) as Schema, JSON.parse(instance) as Json, "", "", errors);
  return errors.sort((a, b) => order(a[0], b[0]) || order(a[1], b[1]));
}
validate.test.ts 72 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/validate-data-against-a-schema/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { validate } from "./validate.ts";

// [case, schema, instance, the failed [instance location, keyword location] pairs]
const cases: [string, string, string, [string, string][]][] = [
  ["valid-object", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": 36}", []],
  ["missing-required", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\"}", [["", "/required"]]],
  ["wrong-member-type", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": \"36\"}", [["/age", "/properties/age/type"]]],
  ["below-minimum", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": -1}", [["/age", "/properties/age/minimum"]]],
  ["two-errors", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"\", \"age\": 3.5}", [["/age", "/properties/age/type"], ["/name", "/properties/name/minLength"]]],
  ["array-items", "{\"type\": \"array\", \"items\": {\"type\": \"string\"}}", "[\"a\", 1, \"c\", null]", [["/1", "/items/type"], ["/3", "/items/type"]]],
  ["no-additional", "{\"properties\": {\"id\": {\"type\": \"integer\"}}, \"additionalProperties\": false}", "{\"id\": 1, \"admin\": true}", [["/admin", "/additionalProperties"]]],
  ["integer-from-fraction-zero", "{\"type\": \"integer\"}", "1.0", []],
  ["integer-from-exponent", "{\"type\": \"integer\"}", "1e2", []],
  ["integer-with-fraction", "{\"type\": \"integer\"}", "3.5", [["", "/type"]]],
  ["boolean-not-integer", "{\"type\": \"integer\"}", "true", [["", "/type"]]],
  ["boolean-not-number", "{\"type\": \"number\"}", "false", [["", "/type"]]],
  ["integer-is-number", "{\"type\": \"number\"}", "3", []],
  ["null-not-object", "{\"type\": \"object\"}", "null", [["", "/type"]]],
  ["array-not-object", "{\"type\": \"object\"}", "[]", [["", "/type"]]],
  ["type-list-match", "{\"type\": [\"string\", \"null\"]}", "null", []],
  ["type-list-miss", "{\"type\": [\"string\", \"null\"]}", "5", [["", "/type"]]],
  ["max-length-astral", "{\"maxLength\": 1}", "\"😀\"", []],
  ["min-length-astral", "{\"minLength\": 2}", "\"\\ud83d\\ude00\"", [["", "/minLength"]]],
  ["combining-mark", "{\"maxLength\": 1}", "\"e\\u0301\"", [["", "/maxLength"]]],
  ["other-type-keywords", "{\"minimum\": 5, \"required\": [\"a\"], \"items\": false}", "\"abc\"", []],
  ["other-type-keywords-number", "{\"maxLength\": 1, \"required\": [\"a\"], \"additionalProperties\": false}", "3", []],
  ["unknown-keyword", "{\"minimun\": 5}", "1", []],
  ["format-is-annotation", "{\"type\": \"string\", \"format\": \"email\"}", "\"not an email\"", []],
  ["true-schema", "true", "{\"a\": [1]}", []],
  ["false-schema", "false", "{}", [["", ""]]],
  ["empty-schema", "{}", "null", []],
  ["false-member-schema", "{\"properties\": {\"a\": false}}", "{\"a\": 0, \"b\": 0}", [["/a", "/properties/a"]]],
  ["pointer-escape", "{\"properties\": {\"a/b\": {\"type\": \"string\"}, \"m~n\": {\"type\": \"string\"}}}", "{\"a/b\": 1, \"m~n\": 2}", [["/a~1b", "/properties/a~1b/type"], ["/m~0n", "/properties/m~0n/type"]]],
  ["pointer-escape-order", "{\"properties\": {\"~1\": false}}", "{\"~1\": 0}", [["/~01", "/properties/~01"]]],
  ["nested-items", "{\"items\": {\"items\": {\"type\": \"integer\"}}}", "[[1, \"x\"], [2]]", [["/0/1", "/items/items/type"]]],
  ["additional-schema", "{\"properties\": {\"id\": {}}, \"additionalProperties\": {\"type\": \"string\"}}", "{\"id\": 1, \"a\": \"x\", \"b\": 2}", [["/b", "/additionalProperties/type"]]],
  ["absent-property", "{\"properties\": {\"a\": {\"type\": \"string\"}}}", "{}", []],
  ["required-all-missing", "{\"required\": [\"a\", \"b\", \"c\"]}", "{}", [["", "/required"]]],
  ["required-null-member", "{\"required\": [\"a\"]}", "{\"a\": null}", []],
  ["inclusive-bounds", "{\"items\": {\"minimum\": 0, \"maximum\": 10}}", "[0, 10, 10.5, -0.5]", [["/2", "/items/maximum"], ["/3", "/items/minimum"]]],
  ["negative-zero", "{\"minimum\": 0}", "-0", []],
  ["fraction-minimum", "{\"minimum\": 0.5}", "0.4", [["", "/minimum"]]],
  ["index-order", "{\"items\": {\"type\": \"string\"}}", "[0, \"\", 0, \"\", \"\", \"\", \"\", \"\", \"\", \"\", 0]", [["/0", "/items/type"], ["/10", "/items/type"], ["/2", "/items/type"]]],
  ["keyword-order", "{\"type\": \"string\", \"minimum\": 5}", "3", [["", "/minimum"], ["", "/type"]]],
  ["inherited-name", "{\"required\": [\"toString\", \"constructor\"]}", "{}", [["", "/required"]]],
  ["proto-member", "{\"properties\": {\"__proto__\": {\"type\": \"string\"}}}", "{\"__proto__\": 1}", [["/__proto__", "/properties/__proto__/type"]]],
  ["non-ascii-name", "{\"required\": [\"é\"], \"properties\": {\"日本\": {\"type\": \"integer\"}}}", "{\"é\": 1, \"日本\": \"x\"}", [["/日本", "/properties/日本/type"]]],
  ["deep-path", "{\"properties\": {\"a\": {\"items\": {\"properties\": {\"b\": {\"required\": [\"c\"]}}}}}}", "{\"a\": [{\"b\": {}}, {\"b\": {\"c\": 1}}, {\"b\": {}}]}", [["/a/0/b", "/properties/a/items/properties/b/required"], ["/a/2/b", "/properties/a/items/properties/b/required"]]],
];

// [case, schema, instance]; one of the texts is not JSON
const invalid: [string, string, string][] = [
  ["trailing-comma", "{\"type\": \"array\"}", "[1, 2,]"],
  ["nan", "{\"type\": \"number\"}", "NaN"],
  ["empty-instance", "{}", ""],
  ["bad-schema", "{\"type\": ", "1"],
  ["single-quotes", "{}", "{'a': 1}"],
];

for (const [name, schema, instance, want] of cases) {
  test(name, () => assert.deepEqual(validate(schema, instance), want));
}

for (const [name, schema, instance] of invalid) {
  test(name, () => assert.throws(() => validate(schema, instance), SyntaxError));
}
validate.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/validate-data-against-a-schema/.

// Package schema checks a JSON value against a small part of JSON Schema 2020-12.
package schema

import (
	"cmp"
	"encoding/json"
	"math"
	"slices"
	"strconv"
	"strings"
	"unicode/utf8"
)

// Failure is the instance location and the keyword location of one failed assertion.
type Failure [2]string

// RFC 6901: "~" becomes "~0" first, then "/" becomes "~1".
var escaper = strings.NewReplacer("~", "~0", "/", "~1")

func pointer(name string) string { return "/" + escaper.Replace(name) }

func kinds(value any) []string {
	switch v := value.(type) {
	case nil:
		return []string{"null"}
	case bool:
		return []string{"boolean"}
	case float64:
		if v == math.Trunc(v) {
			return []string{"integer", "number"}
		}
		return []string{"number"}
	case string:
		return []string{"string"}
	case []any:
		return []string{"array"}
	}
	return []string{"object"}
}

func check(schema, value any, here, at string, errors *[]Failure) {
	switch s := schema.(type) {
	case bool:
		if !s {
			*errors = append(*errors, Failure{here, at})
		}
		return
	case map[string]any:
		if t, ok := s["type"]; ok {
			allowed, _ := t.([]any)
			if name, ok := t.(string); ok {
				allowed = []any{name}
			}
			if !slices.ContainsFunc(kinds(value), func(k string) bool { return slices.Contains(allowed, any(k)) }) {
				*errors = append(*errors, Failure{here, at + "/type"})
			}
		}
		switch v := value.(type) {
		case float64:
			if m, ok := s["minimum"].(float64); ok && v < m {
				*errors = append(*errors, Failure{here, at + "/minimum"})
			}
			if m, ok := s["maximum"].(float64); ok && v > m {
				*errors = append(*errors, Failure{here, at + "/maximum"})
			}
		case string:
			// len counts bytes. RuneCountInString counts code points.
			n := float64(utf8.RuneCountInString(v))
			if m, ok := s["minLength"].(float64); ok && n < m {
				*errors = append(*errors, Failure{here, at + "/minLength"})
			}
			if m, ok := s["maxLength"].(float64); ok && n > m {
				*errors = append(*errors, Failure{here, at + "/maxLength"})
			}
		case map[string]any:
			required, _ := s["required"].([]any)
			for _, name := range required {
				if _, ok := v[name.(string)]; !ok {
					*errors = append(*errors, Failure{here, at + "/required"})
					break
				}
			}
			named, _ := s["properties"].(map[string]any)
			extra, hasExtra := s["additionalProperties"]
			for name, member := range v {
				if sub, ok := named[name]; ok {
					check(sub, member, here+pointer(name), at+"/properties"+pointer(name), errors)
				} else if hasExtra {
					check(extra, member, here+pointer(name), at+"/additionalProperties", errors)
				}
			}
		case []any:
			if items, ok := s["items"]; ok {
				for i, item := range v {
					check(items, item, here+"/"+strconv.Itoa(i), at+"/items", errors)
				}
			}
		}
	}
}

// Validate returns the sorted failures of instance against schema. Both are JSON texts.
func Validate(schema, instance string) ([]Failure, error) {
	var s, v any
	if err := json.Unmarshal([]byte(schema), &s); err != nil {
		return nil, err
	}
	if err := json.Unmarshal([]byte(instance), &v); err != nil {
		return nil, err
	}
	errors := []Failure{}
	check(s, v, "", "", &errors)
	// A map has no order, so the sort makes the result the same on each run.
	slices.SortFunc(errors, func(a, b Failure) int { return cmp.Or(cmp.Compare(a[0], b[0]), cmp.Compare(a[1], b[1])) })
	return errors, nil
}
validate_test.go 83 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/validate-data-against-a-schema/.

package schema

import (
	"slices"
	"testing"
)

func TestCases(t *testing.T) {
	cases := []struct {
		name, schema, instance string
		want                   []Failure
	}{
		{"valid-object", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": 36}", []Failure{}},
		{"missing-required", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\"}", []Failure{{"", "/required"}}},
		{"wrong-member-type", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": \"36\"}", []Failure{{"/age", "/properties/age/type"}}},
		{"below-minimum", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"Ada\", \"age\": -1}", []Failure{{"/age", "/properties/age/minimum"}}},
		{"two-errors", "{\"type\": \"object\", \"required\": [\"name\", \"age\"], \"properties\": {\"name\": {\"type\": \"string\", \"minLength\": 1}, \"age\": {\"type\": \"integer\", \"minimum\": 0}}}", "{\"name\": \"\", \"age\": 3.5}", []Failure{{"/age", "/properties/age/type"}, {"/name", "/properties/name/minLength"}}},
		{"array-items", "{\"type\": \"array\", \"items\": {\"type\": \"string\"}}", "[\"a\", 1, \"c\", null]", []Failure{{"/1", "/items/type"}, {"/3", "/items/type"}}},
		{"no-additional", "{\"properties\": {\"id\": {\"type\": \"integer\"}}, \"additionalProperties\": false}", "{\"id\": 1, \"admin\": true}", []Failure{{"/admin", "/additionalProperties"}}},
		{"integer-from-fraction-zero", "{\"type\": \"integer\"}", "1.0", []Failure{}},
		{"integer-from-exponent", "{\"type\": \"integer\"}", "1e2", []Failure{}},
		{"integer-with-fraction", "{\"type\": \"integer\"}", "3.5", []Failure{{"", "/type"}}},
		{"boolean-not-integer", "{\"type\": \"integer\"}", "true", []Failure{{"", "/type"}}},
		{"boolean-not-number", "{\"type\": \"number\"}", "false", []Failure{{"", "/type"}}},
		{"integer-is-number", "{\"type\": \"number\"}", "3", []Failure{}},
		{"null-not-object", "{\"type\": \"object\"}", "null", []Failure{{"", "/type"}}},
		{"array-not-object", "{\"type\": \"object\"}", "[]", []Failure{{"", "/type"}}},
		{"type-list-match", "{\"type\": [\"string\", \"null\"]}", "null", []Failure{}},
		{"type-list-miss", "{\"type\": [\"string\", \"null\"]}", "5", []Failure{{"", "/type"}}},
		{"max-length-astral", "{\"maxLength\": 1}", "\"😀\"", []Failure{}},
		{"min-length-astral", "{\"minLength\": 2}", "\"\\ud83d\\ude00\"", []Failure{{"", "/minLength"}}},
		{"combining-mark", "{\"maxLength\": 1}", "\"e\\u0301\"", []Failure{{"", "/maxLength"}}},
		{"other-type-keywords", "{\"minimum\": 5, \"required\": [\"a\"], \"items\": false}", "\"abc\"", []Failure{}},
		{"other-type-keywords-number", "{\"maxLength\": 1, \"required\": [\"a\"], \"additionalProperties\": false}", "3", []Failure{}},
		{"unknown-keyword", "{\"minimun\": 5}", "1", []Failure{}},
		{"format-is-annotation", "{\"type\": \"string\", \"format\": \"email\"}", "\"not an email\"", []Failure{}},
		{"true-schema", "true", "{\"a\": [1]}", []Failure{}},
		{"false-schema", "false", "{}", []Failure{{"", ""}}},
		{"empty-schema", "{}", "null", []Failure{}},
		{"false-member-schema", "{\"properties\": {\"a\": false}}", "{\"a\": 0, \"b\": 0}", []Failure{{"/a", "/properties/a"}}},
		{"pointer-escape", "{\"properties\": {\"a/b\": {\"type\": \"string\"}, \"m~n\": {\"type\": \"string\"}}}", "{\"a/b\": 1, \"m~n\": 2}", []Failure{{"/a~1b", "/properties/a~1b/type"}, {"/m~0n", "/properties/m~0n/type"}}},
		{"pointer-escape-order", "{\"properties\": {\"~1\": false}}", "{\"~1\": 0}", []Failure{{"/~01", "/properties/~01"}}},
		{"nested-items", "{\"items\": {\"items\": {\"type\": \"integer\"}}}", "[[1, \"x\"], [2]]", []Failure{{"/0/1", "/items/items/type"}}},
		{"additional-schema", "{\"properties\": {\"id\": {}}, \"additionalProperties\": {\"type\": \"string\"}}", "{\"id\": 1, \"a\": \"x\", \"b\": 2}", []Failure{{"/b", "/additionalProperties/type"}}},
		{"absent-property", "{\"properties\": {\"a\": {\"type\": \"string\"}}}", "{}", []Failure{}},
		{"required-all-missing", "{\"required\": [\"a\", \"b\", \"c\"]}", "{}", []Failure{{"", "/required"}}},
		{"required-null-member", "{\"required\": [\"a\"]}", "{\"a\": null}", []Failure{}},
		{"inclusive-bounds", "{\"items\": {\"minimum\": 0, \"maximum\": 10}}", "[0, 10, 10.5, -0.5]", []Failure{{"/2", "/items/maximum"}, {"/3", "/items/minimum"}}},
		{"negative-zero", "{\"minimum\": 0}", "-0", []Failure{}},
		{"fraction-minimum", "{\"minimum\": 0.5}", "0.4", []Failure{{"", "/minimum"}}},
		{"index-order", "{\"items\": {\"type\": \"string\"}}", "[0, \"\", 0, \"\", \"\", \"\", \"\", \"\", \"\", \"\", 0]", []Failure{{"/0", "/items/type"}, {"/10", "/items/type"}, {"/2", "/items/type"}}},
		{"keyword-order", "{\"type\": \"string\", \"minimum\": 5}", "3", []Failure{{"", "/minimum"}, {"", "/type"}}},
		{"inherited-name", "{\"required\": [\"toString\", \"constructor\"]}", "{}", []Failure{{"", "/required"}}},
		{"proto-member", "{\"properties\": {\"__proto__\": {\"type\": \"string\"}}}", "{\"__proto__\": 1}", []Failure{{"/__proto__", "/properties/__proto__/type"}}},
		{"non-ascii-name", "{\"required\": [\"é\"], \"properties\": {\"日本\": {\"type\": \"integer\"}}}", "{\"é\": 1, \"日本\": \"x\"}", []Failure{{"/日本", "/properties/日本/type"}}},
		{"deep-path", "{\"properties\": {\"a\": {\"items\": {\"properties\": {\"b\": {\"required\": [\"c\"]}}}}}}", "{\"a\": [{\"b\": {}}, {\"b\": {\"c\": 1}}, {\"b\": {}}]}", []Failure{{"/a/0/b", "/properties/a/items/properties/b/required"}, {"/a/2/b", "/properties/a/items/properties/b/required"}}},
	}
	for _, c := range cases {
		got, err := Validate(c.schema, c.instance)
		if err != nil || !slices.Equal(got, c.want) {
			t.Errorf("%s: got %q, %v; want %q", c.name, got, err, c.want)
		}
	}
}

func TestInvalidJSON(t *testing.T) {
	// One of the two texts is not JSON.
	cases := []struct{ name, schema, instance string }{
		{"trailing-comma", "{\"type\": \"array\"}", "[1, 2,]"},
		{"nan", "{\"type\": \"number\"}", "NaN"},
		{"empty-instance", "{}", ""},
		{"bad-schema", "{\"type\": ", "1"},
		{"single-quotes", "{}", "{'a': 1}"},
	}
	for _, c := range cases {
		if _, err := Validate(c.schema, c.instance); err == nil {
			t.Errorf("%s: no error", c.name)
		}
	}
}

References

  1. A. Wright, H. Andrews, B. Hutton, G. Dennis, JSON Schema: A Media Type for Describing JSON Documents, draft-bhutton-json-schema-01, June 2022, 4.3.2 Boolean JSON Schemas; 6.5 Extending JSON Schema; 10.3.1.2 items; 10.3.2.1 properties; 10.3.2.3 additionalProperties; 12.3 Minimum Information
  2. A. Wright, H. Andrews, B. Hutton, JSON Schema Validation: A Vocabulary for Structural Validation of JSON, draft-bhutton-json-schema-validation-01, June 2022, 6.1.1 type; 6.2.2 maximum; 6.2.4 minimum; 6.3.1 maxLength; 6.3.2 minLength; 6.5.3 required; 7.2 Implementation Requirements
  3. P. Bryan (Ed.), K. Zyp, M. Nottingham (Ed.), RFC 6901: JavaScript Object Notation (JSON) Pointer, April 2013, 3 Syntax
  4. The Python Standard Library, sys, Python 3.14, sys.float_info, dig
  5. jsonschema documentation, Schema Validation, The Basics, jsonschema.validate; the Validator protocol, format_checker
  6. Ajv documentation, Getting started, Basic data validation; Best performance
  7. MDN Web Docs, String length, the introduction
  8. .NET API reference, String.EnumerateRunes Method, Definition
  9. Go standard library, package encoding/json, func Unmarshal
  10. Go standard library, package unicode/utf8, func RuneCount; func RuneCountInString
  11. The Go Programming Language Specification, For statements with range clause
  12. .NET documentation, XML Schema (XSD) Validation with XmlSchemaSet, the example
  13. OWASP Cheat Sheet Series, Input Validation Cheat Sheet, Parse Safely, Then Validate; Validate Structured Data

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source