C.W.K.
Stream
Lesson 04 of 08 · published

Arrays — items, uniqueItems, contains

~10 min · json-schema, arrays, items

Level 0Plaintext
0 XP0/64 lessons0/12 achievements
0/100 XP to next level100 XP to go0% complete

Constraining the elements, the size, and the contents of arrays

items — schema for every element

items is itself a schema. Every element of the array must match it. {"type": "array", "items": {"type": "string"}} means 'array of strings'.

prefixItems — tuple-style validation

Pass an array of schemas to prefixItems to validate position-by-position: position 0 against the first schema, position 1 against the second, etc. Use this for fixed-shape tuples ([latitude, longitude], [year, month, day]). Beyond the prefix, items applies (or set items: false to forbid extras).

Size & uniqueness

  • minItems, maxItems — count bounds.
  • uniqueItems — booleans/strings/numbers easy; objects compared by deep equality.
  • contains — at least one element must match this sub-schema.
Principle: homogeneous arrays use items; tuple-shaped arrays ([latitude, longitude], [r, g, b, a]) use prefixItems. Don't reach for items with a oneOf when prefixItems will do — it's clearer at read-time and catches more position-specific errors.

Code

Homogeneous array of strings·json
{
  "type": "array",
  "items": { "type": "string" },
  "minItems": 1,
  "maxItems": 10,
  "uniqueItems": true
}
Tuple shape (position-aware)·json
{
  "type": "array",
  "prefixItems": [
    { "type": "number", "minimum": -90,  "maximum": 90 },
    { "type": "number", "minimum": -180, "maximum": 180 }
  ],
  "items": false,
  "minItems": 2,
  "maxItems": 2
}
contains — at least one element must match·json
{
  "type": "array",
  "items": { "type": "object" },
  "contains": {
    "type": "object",
    "properties": { "role": { "const": "admin" } },
    "required": ["role"]
  }
}

External links

Exercise

Write a schema for a 'shopping cart' object: items is an array of product entries (each with id, name, qty, price), minItems 1, no duplicates, and at least one item must have qty > 1. Validate one cart that meets the spec and one that fails the 'qty > 1 somewhere' rule. The contains keyword does the heavy lifting.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.