Write a JSON Schema with Examples: A Practical Sample and What to Watch For
A sample JSON Schema with valid and invalid examples, what formatting and validation change, and how copy and paste can quietly break JSON.
A JSON Schema is a JSON document that describes what another JSON document is allowed to contain: which fields exist, what types they hold, which ones are required and what values are acceptable. This guide walks through a sample schema, shows instances that pass and fail it, and explains what formatting and validation tools change. It also covers the copy-and-paste problems that most often turn a correct schema into one that will not parse.
Is a JSON Schema the right tool for your use?
A schema is a good fit when you need a contract that software can check. Examples include validating API requests, catching malformed configuration files before deployment, or generating form and editor hints from one definition. The main benefit is that "the data should look like this" becomes something a validator can enforce, not just something documentation recommends.
The main tradeoff is consistency across tools. JSON Schema has several published drafts, and validators differ in which drafts they support and in how strictly they treat some keywords. A schema that behaves one way in your editor can behave differently in your build pipeline if the two use different validators or settings. You need to pin the draft and test with the validator you will actually run.
Plain text is often the better choice in three cases: you are explaining a data shape to people who will never run a validator, the structure is a one-off, or a single annotated example communicates enough. In those cases, a short prose description next to one realistic sample document is easier to read than a schema. Many teams keep both: the schema for machines and a plain-language summary for people.
A sample JSON Schema
The schema below describes a simple user record. It uses only common keywords, so it works as a starting template.
{
"title": "User",
"description": "A user account record",
"type": "object",
"properties": {
"id": { "type": "integer", "minimum": 1 },
"username": {
"type": "string",
"minLength": 3,
"maxLength": 32,
"pattern": "^[a-z0-9_]+$"
},
"displayName": { "type": "string" },
"createdAt": { "type": "string", "format": "date-time" },
"roles": {
"type": "array",
"items": { "type": "string", "enum": ["admin", "editor", "viewer"] },
"uniqueItems": true
}
},
"required": ["id", "username"],
"additionalProperties": false,
"examples": [
{ "id": 42, "username": "ada_l", "roles": ["editor"] }
]
}
Each keyword in the sample does the following:
- type: the JSON type the value must have, such as object, array, string, integer, number, boolean or null.
- properties: the schema for each named field of an object.
- required: fields that must be present. Fields listed under properties but not here are optional.
- additionalProperties: false rejects any field not listed under properties. Leave it out if you want to allow extra fields.
- minimum, minLength, maxLength and pattern: constraints on numbers and strings. A pattern is a regular expression matched against the string.
- enum: a fixed list of allowed values.
- items and uniqueItems: the schema for each array element, and whether duplicate elements are rejected.
- format: a named format such as date-time. How strictly this is checked depends on the validator; see the caveat below.
- title, description and examples: annotations for people and tools. They do not restrict the data.
In practice, you should also add the $schema keyword at the top. Set it to the dialect identifier of the draft your validator supports, so that tools interpret the keywords the same way. The identifier is a URI published by the JSON Schema project, so copy it from that project's documentation for your chosen draft.
Instances that pass and fail
The following document should validate against the sample schema. Both required fields are present, the types match, the role is in the allowed list, and no extra fields appear.
{
"id": 7,
"username": "grace_h",
"displayName": "Grace",
"createdAt": "2024-05-01T09:30:00Z",
"roles": ["admin", "viewer"]
}
This document should fail, for several separate reasons:
{
"id": 0,
"username": "Grace H",
"roles": ["owner", "owner"],
"nickname": "gh"
}
- id is 0, which is below the minimum of 1.
- username contains an uppercase letter and a space, so it does not match the pattern.
- roles contains "owner", which is not in the enum. It is also repeated, which violates uniqueItems.
- nickname is not a declared property, and additionalProperties is false.
Validators usually report each failure with a path to the failing value. Whether they report all errors or stop at the first one depends on the tool and its settings.
Two caveats that surprise people
First, the examples keyword is an annotation. Validators generally do not check that your examples conform to the schema. An example can drift out of date without any warning. If the examples matter, validate them separately as part of your tests.
Second, format is treated as an annotation by default in recent drafts. Some validators check it only when you enable that explicitly, and some check only certain formats. Do not assume that format: date-time rejects a malformed date until you have confirmed how your validator handles it. If the check is essential, a pattern or application-level validation is more predictable.
What formatting and validation tools actually change
In developer text utilities, "formatting" JSON usually means re-serializing it. Pretty-printing adds indentation and line breaks, and minifying removes them. Validation is different: it reads the document and reports problems without changing it. Neither involves reversing characters, mirroring glyphs or changing fonts. Those are separate kinds of text transformation, and applying them to JSON produces something that is no longer valid JSON.
Whitespace between tokens has no meaning in JSON, so pretty-printing and minifying should not change what a parser reads. Whitespace inside string values is data and must be preserved. Several other changes can happen when a tool parses and rewrites a document:
- Key order: the JSON standard treats object members as unordered, so reordering keys does not change meaning for a compliant parser. It does produce noisy diffs, and code that wrongly depends on order can break.
- Duplicate keys: the standard does not define how they are handled. A formatter may silently keep only one value, so the output hides a problem that existed in the input.
- Numbers: tools that convert numbers to standard floating point can lose precision on very large integers or rewrite values, for example 1.0 as 1. If exact numeric text matters, use a tool that preserves it.
- Escapes: a character written as a \u escape and the same character written directly are equivalent. A tool may convert between the two forms.
Before trusting a formatter with important data, run a small test file containing a duplicate key, a large integer and a non-ASCII string. Compare the output with the input. That shows how this particular tool behaves; it does not tell you how other tools behave.
Does the schema survive copying and sharing?
Most broken schemas arrive that way through copy and paste, not through logic errors. JSON accepts only four whitespace characters outside strings: space, tab, line feed and carriage return. Keys and keywords are matched by exact characters. Text that looks correct can therefore still fail. The most common causes are:
- Curly quotes: word processors and some chat or document tools replace straight double quotes with typographic ones, which JSON does not accept.
- Non-breaking and zero-width spaces: these can come along when copying from web pages or rich-text editors. They are invisible but invalid outside strings, and inside a key they make it a different key.
- Byte order marks: the JSON standard says generators must not add one at the start of a document. Parsers may or may not ignore one.
- Styled "font" characters: generators that produce bold, italic or script-looking text do this by substituting different Unicode characters. A key written that way looks right but will not match the plain key a validator expects.
- Comments and trailing commas: some editors accept these in looser JSON-like formats, but standard JSON parsers reject them.
The safest way to share a schema is as a plain-text file or a code block that preserves characters exactly. If you are unsure, paste it into a validator before relying on it. Do not share a schema as a screenshot: nobody can copy it, search it or check it, and screen readers cannot read it as text.
Readability is also a concern. Indentation helps sighted readers follow nesting, but deeply nested schemas are hard to follow, especially when listened to line by line. Some ways to keep a schema usable:
- Keep nesting shallow.
- Move repeated structures into named definitions and reference them.
- Use description fields to say in words what each part is for.
- For readers who do not work with JSON, write a plain-language summary of the required fields and rules alongside the schema.
Gaps in this review
This guide does not report any tests of specific validators, editors, sharing platforms or assistive technologies. No measurements were available. Statements about format checking, error reporting and copy-and-paste behavior describe common patterns, not confirmed results for a particular product. Check the documentation of the validator and draft you use, and test your schema in the environments where it will actually be read and run.