Part 3 of 11
JSON Schema
JSON Schema is widely used to describe data that systems exchange or store, for example in API definitions, schema registries, and database validation.
- Types: null, boolean, text strings, numbers, integers, arrays, and objects.
- Validation rules: limits on values, like "a percentage must be between 0 and 100".
It has two ways to treat fields the schema does not list:
| Model | Unknown fields | Notes |
|---|---|---|
| Open content model | Allowed, of any type | The default (additionalProperties is true) |
| Closed content model | Not allowed | Only listed fields may appear |
Because the default is open, a JSON Schema mostly describes what is not allowed, rather than every field that is.
It can get awkward fast. JSON object keys are always strings. So to describe a map from numeric product IDs to names, you need a key pattern that allows only digits, and you must close off all other keys. JSON Schema also has if/else conditions, named types, and references to schemas stored elsewhere. That makes it powerful but unwieldy: remote references are hard to resolve, conditions are hard to reason about, and changing a schema safely is hard. XML Schema has the same kind of problems.
Binary JSON
JSON is shorter than XML, but both are large next to binary formats. So binary versions of JSON exist, like MessagePack, CBOR, and BSON, and binary versions of XML too. None is used very widely.
- Some add types JSON lacks, such as separate integers and floats, or binary strings.
- But they keep the JSON data model, and they have no schema.
- So every record must still include every field name.
Take a small record with a city of "Pune", a zip code of 411001, and two tags, "cafe" and "wifi". In MessagePack:
- One byte says "a map with 3 entries".
- One byte says "a string of 4 bytes", followed by the 4 bytes of
city. - The value "Pune" follows the same way: a length byte, then the letters.
- The zip code takes a type byte plus 4 bytes, and the tags list starts with one byte saying "an array of 2 items".
Length prefixes mean there is no need for quote marks, closing brackets, or escaping. The record is 51 bytes as compact JSON and 36 bytes in MessagePack. That is a modest saving, and you give up being able to read the data by eye. Formats with a schema can do much better, as the next sections show.