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.
- Evidence
- Code in 5 languages
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:
typeaccepts a value of one of the given types:null,boolean,object,array,number,stringorinteger. The typeinteger"matches any number with a zero fractional part"2, so1.0is an integer.minimumandmaximumare inclusive limits for a number.minLengthandmaxLengthare 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.requiredgives the names that an object must have.propertiesgives a schema for the member of each name, if the member exists.additionalPropertiesgives a schema for each member thatpropertiesdoes not name.itemsgives 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.loadsmakestrueabool, andboolis a subclass ofint. Thus the solution tests forboolbeforeint. Afloatis an integer whenis_integer()returnsTrue.lencounts the code points of a string. - JavaScript and TypeScript (Node.js).
typeof nullandtypeof []both give"object", so the solution tests fornullandArray.isArrayfirst.Number.isIntegertests for a zero fractional part. Thelengthof a string is its length "in UTF-16 code units"7, so the solution counts the code points with the spread syntax[...value]. It usesObject.hasOwnfor each name, because the operatorinalso finds inherited names such astoString. - C#.
JsonDocument.Parsegives a tree ofJsonElementvalues, andValueKindgives the type of each value.EnumerateRunesreturns "an enumeration of Rune from this string"8, one for each code point, and the solution counts them.string.CompareOrdinalsorts by UTF-16 code units, which agrees with code point order under the contract. - Go.
json.Unmarshalinto ananystores abool, afloat64, astring, a[]any, amap[string]anyornil9, and a type switch selects the keywords for each.lencounts the bytes of a string, andutf8.RuneCountInStringcounts 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()) { }
}
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-exponentandinteger-with-fraction:1.0and1e2are integers, and3.5is not.boolean-not-integerandboolean-not-number:trueandfalseare booleans, not numbers.null-not-objectandarray-not-object:nulland[]are not objects.type-list-matchandtype-list-miss:{"type": ["string", "null"]}acceptsnulland rejects5.max-length-astral,min-length-astralandcombining-mark: the emoji U+1F600 has the length 1, also when the text writes it as two escapes. The lettereand the combining acute accent U+0301 have the length 2.other-type-keywordsandother-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-keywordandformat-is-annotation:{"minimun": 5}accepts1, and{"format": "email"}accepts any string.true-schema,false-schema,empty-schemaandfalse-member-schema: the schemafalsefails at its own location, which is the empty pointer at the root.pointer-escapeandpointer-escape-order: the namesa/b,m~nand~1becomea~1b,m~0nand~01in the pointers.absent-property,required-all-missingandrequired-null-member: a missing member is not an error forproperties. Three missing names give one error forrequired. A member with the valuenullexists.inclusive-bounds,negative-zeroandfraction-minimum:0and10pass the limits 0 and 10, and-0passes the minimum 0.index-orderandkeyword-order: the pointer/10sorts before/2, and/minimumsorts before/type.inherited-nameandproto-member: the namestoString,constructorand__proto__are normal names.non-ascii-name,nested-itemsanddeep-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
propertiesis 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 inrequired. To reject other members, setadditionalPropertiestofalse. The casesabsent-propertyandno-additionalshow 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. -
formatdoes not validate by default. In JSON Schema 2020-12, the value offormatis 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
integerwithisinstanceacceptstrueand rejects1.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))
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.
lengthcounts UTF-16 code units,typeofgives"object"fornulland for an array, andinfinds 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"));
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.
Related tasks
- JSON Schema: the format, its versions and its libraries.
- Read and write JSON: parse a JSON text and get a value at a path.
- JSON Pointer: the syntax of the two locations.
- Deserialization of untrusted data: parse untrusted data into values, not objects.
- UTF-8: the bytes of the strings whose code points the length counts.
- Sort a list of records: sort records by two keys.
Code
The build runs the native tests of each language in a pinned toolchain.
# 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)
// 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);
}
}
// 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));
}
// 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));
}
// 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
- 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
- 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
- P. Bryan (Ed.), K. Zyp, M. Nottingham (Ed.), RFC 6901: JavaScript Object Notation (JSON) Pointer, April 2013, 3 Syntax
- The Python Standard Library, sys, Python 3.14, sys.float_info, dig
- jsonschema documentation, Schema Validation, The Basics, jsonschema.validate; the Validator protocol, format_checker
- Ajv documentation, Getting started, Basic data validation; Best performance
- MDN Web Docs, String length, the introduction
- .NET API reference, String.EnumerateRunes Method, Definition
- Go standard library, package encoding/json, func Unmarshal
- Go standard library, package unicode/utf8, func RuneCount; func RuneCountInString
- The Go Programming Language Specification, For statements with range clause
- .NET documentation, XML Schema (XSD) Validation with XmlSchemaSet, the example
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 84C7XS Edit this page History Report an error Markdown