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

Objects — additionalProperties, patternProperties

~10 min · json-schema, objects, additional-properties

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

The properties you didn't list still need a policy

additionalProperties

By default, properties not listed in properties are allowed. To forbid them, set additionalProperties: false — the schema becomes 'closed'. To validate them against a sub-schema instead, set additionalProperties to a schema (e.g. { "type": "string" }: 'every other key must be a string').

patternProperties

Sometimes property names follow a pattern. patternProperties maps regex-on-key to a schema. "^env_": {"type": "string"} means 'every key starting with env_ must be a string'. The classic use: env-var maps, locale maps ("^[a-z]{2}(-[A-Z]{2})?$").

propertyNames

Constrain the key strings themselves: "propertyNames": {"pattern": "^[a-zA-Z_][a-zA-Z0-9_]*$"} means 'all keys must be valid identifiers'. Useful when JSON keys become variable names downstream.

'closed by default' costs you forwards-compatibility. A schema with additionalProperties: false rejects valid v2 documents in a v1 validator. Public APIs usually leave it open (or document the policy explicitly); private internal schemas often close it. Pick consciously, not by reflex.

Code

additionalProperties: false (closed schema)·json
{
  "type": "object",
  "properties": {
    "id":   { "type": "integer" },
    "name": { "type": "string" }
  },
  "required": ["id", "name"],
  "additionalProperties": false
}
additionalProperties as a schema (typed map)·json
{
  "type": "object",
  "properties": {
    "name":  { "type": "string" },
    "email": { "type": "string" }
  },
  "additionalProperties": { "type": "string" }
}
patternProperties — keys matching a regex·json
{
  "type": "object",
  "patternProperties": {
    "^env_":     { "type": "string" },
    "_count$":   { "type": "integer", "minimum": 0 }
  },
  "additionalProperties": false
}
propertyNames — constrain the keys themselves·json
{
  "type": "object",
  "propertyNames": {
    "pattern": "^[a-zA-Z_][a-zA-Z0-9_]*$"
  },
  "additionalProperties": { "type": "any" }
}

External links

Exercise

Take a config schema you control. Decide for each top-level: closed or open. For one of them, add additionalProperties: false, deliberately misspell a key in your config file, and watch the validator catch it. The first time this saves you from a 30-minute debug session, you'll be a believer.

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.