XML technologies / JSON for XML professionals / Validation and business rules

Those coming from the XML world know the distinction between well-formedness and validity. The distinction is just as important for JSON. A parser can confirm that a document is syntactically readable. Whether a book title is present, a date exists or a cross-reference can be resolved are additional questions. The package therefore separates parsing, structural validation and business rules.

What JSON Schema describes

JSON Schema can express constraints on types, properties, required fields and cardinalities, among other things. properties describes fields but does not automatically make them mandatory. That is the purpose of required. Unknown object members are not generally prohibited unless an appropriate restriction is specified. The book model therefore uses the following setting for the relevant objects: additionalProperties: false. [Q19]

The complete schema for the example book:

File: schemas/book.schema.json

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.org/data2type/schemas/book-1.json",
  "title": "data2type publication demo record",
  "type": "object",
  "additionalProperties": false,
  "required": [
    "id",
    "title",
    "language",
    "published",
    "available",
    "price",
    "authors",
    "keywords",
    "publisher",
    "isbn"
  ],
  "properties": {
    "id": {
      "type": "string",
      "pattern": "^book-[0-9]{3}$"
    },
    "title": {
      "type": "string",
      "minLength": 1
    },
    "language": {
      "type": "string",
      "enum": [
        "en",
        "de",
        "es"
      ]
    },
    "published": {
      "type": "string",
      "format": "date"
    },
    "available": {
      "type": "boolean"
    },
    "price": {
      "$ref": "#/$defs/price"
    },
    "authors": {
      "type": "array",
      "minItems": 1,
      "items": {
        "$ref": "#/$defs/author"
      }
    },
    "keywords": {
      "type": "array",
      "items": {
        "type": "string",
        "minLength": 1
      },
      "uniqueItems": true
    },
    "subtitle": {
      "type": [
        "string",
        "null"
      ]
    },
    "publisher": {
      "type": "string",
      "minLength": 1
    },
    "isbn": {
      "type": "string",
      "pattern": "^[0-9]{13}$"
    }
  },
  "$defs": {
    "price": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "amount",
        "currency"
      ],
      "properties": {
        "amount": {
          "type": "string",
          "pattern": "^(0|[1-9][0-9]*)\\.[0-9]{2}$"
        },
        "currency": {
          "const": "EUR"
        }
      }
    },
    "author": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "id",
        "name"
      ],
      "properties": {
        "id": {
          "type": "string",
          "pattern": "^person-[0-9]{3}$"
        },
        "name": {
          "type": "string",
          "minLength": 1
        }
      }
    }
  }
}

The $schema declaration identifies the schema dialect used, in this case Draft 2020-12. $id identifies the schema; it is not the ID of the book being described. $ref refers in this example to reusable schema components under $defs. This reference is not a business relationship to a person either. A data reference and a schema reference are different things.

The price is deliberately validated as a string using a restrictive pattern. Authors remain an array, even when there is exactly one entry. subtitle may be a string or null and is not required. The original bibliographic record contains the actual subtitle; the separate null-value file is an exercise copy. The ISBN is modeled as a 13-digit string. The pattern checks only its shape, not the ISBN check digit. These decisions express the example contract; they are not inevitable consequences of JSON syntax.

Validation does not automatically perform conversion

A string "true" is not automatically converted by a schema with type: "boolean" to true. Likewise, a default annotation does not automatically insert missing values. Some tools offer additional functions for such changes; these must then be deliberately enabled and documented as a separate processing step. [Q20]

For format special care is required. In Draft 2020-12, annotations must be distinguished from actively supported format validation. A schema with format: "date" does not guarantee, independently of the vocabulary and validator configuration, that every implementation rejects an impossible calendar date. The example explicitly enables validation with FormatChecker. [Q20], [Q21]

File: examples/python/validate.py

"""JSON Schema checks plus a separate business rule."""
import json
from pathlib import Path
from jsonschema import Draft202012Validator, FormatChecker
from strict_json import load_json

ROOT = Path(__file__).resolve().parents[2]
SCHEMA = load_json(ROOT / "schemas/book.schema.json")
Draft202012Validator.check_schema(SCHEMA)
VALIDATOR = Draft202012Validator(SCHEMA, format_checker=FormatChecker())

def errors_for(book):
    errors = [f"{error.json_path}: {error.message}"
              for error in sorted(VALIDATOR.iter_errors(book),
                                  key=lambda e: str(e.json_path))]
    if errors:
        return errors
    ids = [author["id"] for author in book["authors"]]
    if len(ids) != len(set(ids)):
        errors.append("$.authors: author identifiers must be unique")
    return errors

if __name__ == "__main__":
    errors = errors_for(load_json(ROOT / "data/book.json"))
    print(json.dumps({"valid": not errors, "errors": errors}, indent=2))
    raise SystemExit(bool(errors))

For the valid book, the expected message is valid: true. For the file containing 2026-02-30 the actual test produces:

File: results/core/book-invalid-date.errors.json

[
  "$.published: '2011-02-30' is not a 'date'"
]

And for a Boolean value supplied as a string:

File: results/core/book-string-boolean.errors.json

[
  "$.available: 'true' is not of type 'boolean'"
]

The tests also distinguish a missing title, an unknown field and a duplicate author ID. These negative cases are not an afterthought at the end of a project; they form part of the data contract’s definition.

What can and cannot be compared with XSD

The XML version has its own deliberately simple XSD:

File: schemas/book.xsd

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="book">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="title" type="xs:string"/>
        <xs:element name="language" type="xs:language"/>
        <xs:element name="published" type="xs:date"/>
        <xs:element name="price">
          <xs:complexType>
            <xs:simpleContent>
              <xs:extension base="xs:decimal">
                <xs:attribute name="currency" type="xs:string" use="required"/>
              </xs:extension>
            </xs:simpleContent>
          </xs:complexType>
        </xs:element>
        <xs:element name="authors">
          <xs:complexType><xs:sequence>
            <xs:element name="author" minOccurs="1" maxOccurs="unbounded">
              <xs:complexType><xs:sequence><xs:element name="name" type="xs:string"/></xs:sequence>
                <xs:attribute name="id" type="xs:ID" use="required"/>
              </xs:complexType>
            </xs:element>
          </xs:sequence></xs:complexType>
        </xs:element>
        <xs:element name="keywords">
          <xs:complexType><xs:sequence>
            <xs:element name="keyword" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence></xs:complexType>
        </xs:element>
        <xs:element name="subtitle" type="xs:string" minOccurs="0" nillable="true"/>
        <xs:element name="publisher" type="xs:string"/>
        <xs:element name="isbn" type="xs:string"/>
      </xs:sequence>
      <xs:attribute name="id" type="xs:ID" use="required"/>
      <xs:attribute name="available" type="xs:boolean" use="required"/>
    </xs:complexType>
  </xs:element>
</xs:schema>

Both schemas successfully validate the example and reject an impossible date. However, they are explicitly not fully equivalent rule sets. For example, the XSD uses xs:language, xs:decimal and xs:ID, whereas parts of the JSON Schema are more tightly tailored to the example profile. In this teaching example, the XSD also allows other currency strings; the JSON Schema allows only EUR. A dedicated test demonstrates this difference.

This limitation is important for teaching: a comparison of two technologies should not conceal differences by presenting two only approximately matching schemas as equivalent. A production migration would require an explicit rule table specifying which constraints must be identical on both sides. Only then would a reliable comparison of validity be possible.

XSD describes XML content models and data types; JSON Schema describes conditions on JSON instances. Both tools are tied to their respective data models. Mechanically translating every rule is therefore neither possible nor necessarily useful. [Q40], [Q41]

Business rules remain a separate layer

An author ID must not occur more than once in the book model. uniqueItems: true would only check the uniqueness of complete array entries, not, in general, the uniqueness of a particular field within otherwise different objects. The example validation therefore checks the list of IDs separately after structural validation.

A cross-reference must also point to an existing section. A string pattern can confirm that chapter-2 looks like a suitable ID. It cannot establish whether that section exists in the current collection. For XML, the package provides a Schematron rule:

File: schemas/article.sch

<schema xmlns="http://purl.oclc.org/dsdl/schematron" queryBinding="xslt">
  <pattern id="references">
    <rule context="xref">
      <assert test="@target = //section/@id">A cross-reference must target an existing section.</assert>
    </rule>
    <rule context="*[@id]">
      <assert test="count(//*[@id = current()/@id]) = 1">Identifiers must be unique.</assert>
    </rule>
  </pattern>
</schema>

For the JSON AST, the test similarly uses a set of known section IDs. A deliberately broken reference produces:

File: results/core/rich-reference-errors.json

[
  "Unknown reference target: missing-section"
]

This combination is not a drawback of JSON Schema. It is a clear division of responsibilities: shape and local values on one side, consistency across a collection or business consistency on the other. In the RDF context, another layer is added. SHACL can check relationships and constraints in a graph rather than merely checking the particular JSON-LD notation.

Modular JSON schemas also require attention to the scope of keywords. additionalProperties does not automatically know all properties described in arbitrary other allOf branches. For composite models, unevaluatedProperties may be appropriate, but this requires a validator that correctly supports the chosen dialect. [Q19]

back to top