JSON and data guides

JSON Schema patternProperties: validate dynamic keys

Constrain names and values in map-like objects, accounting for unanchored patterns and overlapping matches.

Nav Tools ·

Describe a map rather than fixed fields

patternProperties maps name patterns to value schemas. It is useful when keys are dynamic but have an agreed prefix.

The example accepts metric names beginning with m_ followed by lowercase letters, with numeric values.

{"type":"object","patternProperties":{"^m_[a-z]+
quot;:{"type":"number"}},"additionalProperties":false} {"m_latency":12} → valid {"m_latency":"12"} → invalid

Anchor the entire name

JSON Schema patterns are not implicitly anchored. Without ^ and $, a matching substring can allow an unexpected prefix or suffix.

Use Regex Tester on accepted and rejected names before embedding the pattern in the schema. Account for the site's JavaScript regex flavor.

Multiple patterns can apply

If a name matches two patterns, its value must satisfy both schemas. A match is not a first-branch-wins selection.

For example, a broad numeric prefix rule and a narrower integer rule both constrain the narrower key. Avoid contradictory overlaps.

Separate names from quantities

Use minProperties or maxProperties for the number of entries; patternProperties only constrains matching entries. An empty object passes the example.

Use propertyNames if every key needs a naming rule regardless of its value schema. Test unknown keys as well as wrong values.

References

← JSON and data guides