JSON Schema patternProperties and if/then for Dynamic Keys: Replacing Manual Validation Loops
patternProperties constrains value types by key-name regex, if/then adds conditional requirements driven by a discriminator, and unevaluatedProperties closes the schema when composition is involved.
On this page
The short answer
Use patternProperties to enforce that keys matching a naming convention carry the correct value type, if/then to require additional fields based on a discriminator value, and unevaluatedProperties:false to reject any key not covered by a declared rule. Together these three keywords replace hand-written Python validation loops that enumerate every possible key name.
Why manual validation of dynamic keys is fragile and schema-level rules are preferable
When a JSON object contains keys generated at runtime, such as prefixed identifiers or user-defined tags, hand-written Python validation loops must enumerate every possible key name or rely on ad-hoc string checks. The Python json module guarantees that all keys are strings after serialization, but it provides no mechanism to constrain which string keys are legal or what value types they must hold. JSON Schema's patternProperties keyword moves this responsibility into a declarative contract that validators enforce before application code runs.
The json documentation states explicitly: Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are converted to strings. This means the schema layer is the only place where key-name constraints can be expressed without custom code.
import json
from jsonschema import Draft202012Validator
# The json module decodes keys as str but performs zero schema validation.
raw = '{"S_tag": "hello", "I_count": 7, "source": "web"}'
payload = json.loads(raw)
print(type(list(payload.keys())[0])) # <class 'str'>Practical tip
Always anchor your patternProperties regexes with ^ and $ unless you intentionally want substring matching. An unanchored pattern like "S_" will match "myS_tag" and "S_extra" alike, which is rarely what you want for a prefix convention.
patternProperties: constraining value types by key name pattern
patternProperties accepts a map from regular expressions to schemas. Any instance key matching a regex must satisfy the associated schema. The official documentation demonstrates ^S_ requiring strings and ^I_ requiring integers. The critical detail is that the regex matches anywhere within the key name unless anchored with ^ and $, so an unanchored pattern like "p" will match "apple" unintentionally. This is the primary tool for dynamic keys whose names follow a naming convention.
Keys that do not match any pattern are simply ignored by patternProperties; they fall through to additionalProperties or are accepted by default.
schema = {
"type": "object",
"patternProperties": {
"^S_": {"type": "string"},
"^I_": {"type": "integer"}
}
}
ok = {"S_25": "This is a string", "I_0": 42}
bad = {"S_0": 42} # starts with S_ but value is not a string
print(list(Draft202012Validator(schema).iter_errors(ok))) # []
print(list(Draft202012Validator(schema).iter_errors(bad))) # 1 ValidationErrorCombining patternProperties with properties for known and unknown keys
A schema can simultaneously declare fixed keys via properties and dynamic keys via patternProperties. The documentation provides a concrete example: a builtin key constrained to number via properties, while ^S_ and ^I_ prefixes are constrained via patternProperties. Keys matching neither pattern fall through to additionalProperties. This layered approach replaces the common anti-pattern of a single validation function that checks known keys in one branch and unknown keys in another.
The evaluation order is: properties handles exact-match keys, patternProperties handles regex-match keys, and additionalProperties handles everything else. Each keyword operates independently on its subset of keys.
schema = {
"type": "object",
"properties": {"builtin": {"type": "number"}},
"patternProperties": {
"^S_": {"type": "string"},
"^I_": {"type": "integer"}
},
"additionalProperties": {"type": "string"}
}
# "keyword" matches no pattern, so additionalProperties applies
print(list(Draft202012Validator(schema).iter_errors({"keyword": "value"}))) # []
print(list(Draft202012Validator(schema).iter_errors({"keyword": 42}))) # 1 erroradditionalProperties as the catch-all for unmatched keys
additionalProperties validates keys that are not matched by properties or patternProperties. Setting it to false rejects any key outside the declared set. Setting it to a schema constrains the value type of all remaining keys without enumerating them. The documentation shows that a key keyword with value 42 fails when additionalProperties is {"type":"string"}. This keyword is the safety net that prevents arbitrary junk from entering the object.
A common mistake is assuming additionalProperties sees properties declared in sibling subschemas reached through allOf. It does not. It only recognizes properties in its own subschema, which is why unevaluatedProperties exists.
schema = {
"type": "object",
"properties": {"name": {"type": "string"}},
"additionalProperties": False
}
print(list(Draft202012Validator(schema).iter_errors({"name": "ok"})))
print(list(Draft202012Validator(schema).iter_errors({"name": "ok", "age": 30})))if/then for conditional field requirements driven by a discriminator value
The if/then/else construct handles scenarios where the presence or type of certain keys depends on the value of another key. The documentation's address example uses if to check whether type equals business, then requires a department property. This replaces manual Python code that would read the discriminator, branch, and validate conditionally.
The key insight is that then only adds constraints when if matches, enabling per-variant validation without separate schemas per variant. The if subschema must include required to ensure the discriminator key is actually present; otherwise an absent key trivially satisfies the properties check and then fires unexpectedly.
schema = {
"type": "object",
"properties": {"type": {"enum": ["residential", "business"]}},
"required": ["type"],
"if": {
"properties": {"type": {"const": "business"}},
"required": ["type"]
},
"then": {
"properties": {"department": {"type": "string"}},
"required": ["department"]
}
}
biz = {"type": "business", "department": "HR"}
res = {"type": "residential"}
print(list(Draft202012Validator(schema).iter_errors(biz))) # []
print(list(Draft202012Validator(schema).iter_errors(res))) # []
print(list(Draft202012Validator(schema).iter_errors({"type": "business"}))) # 1 errorunevaluatedProperties to close the schema when if/then and allOf interact
The well-known pitfall is that additionalProperties only sees properties declared in its own subschema, so extending a closed schema via allOf causes false rejections. The documentation demonstrates that a type property added in an outer schema is rejected by an inner additionalProperties:false. The fix is unevaluatedProperties:false, which recognizes properties evaluated by all combined subschemas including those introduced by then.
This keyword requires JSON Schema draft 2019-09 or later. In the Python jsonschema library, use Draft201909Validator or Draft202012Validator. Older drafts must rely on additionalProperties with manual property enumeration in every subschema, which defeats the purpose of composition.
schema = {
"type": "object",
"properties": {"source": {"enum": ["web", "queue"]}},
"required": ["source"],
"if": {
"properties": {"source": {"const": "web"}},
"required": ["source"]
},
"then": {"properties": {"url": {"type": "string"}}, "required": ["url"]},
"else": {"properties": {"queue_name": {"type": "string"}}, "required": ["queue_name"]},
"patternProperties": {
"^S_": {"type": "string"},
"^I_": {"type": "integer"}
},
"additionalProperties": {"type": "string"},
"unevaluatedProperties": False
}
good = {"source": "web", "url": "https://example.com", "S_tag": "hi", "I_n": 1}
bad = {"source": "web", "url": "x", "S_tag": 42}
print(list(Draft202012Validator(schema).iter_errors(good))) # []
print(list(Draft202012Validator(schema).iter_errors(bad))) # 1 errorminProperties and maxProperties to bound the cardinality of dynamic keys
patternProperties constrains what dynamic keys look like but not how many exist. minProperties and maxProperties set integer bounds on the total number of keys in the object. The documentation shows a schema with minProperties:2 and maxProperties:3 that rejects empty objects, single-key objects, and four-key objects while accepting two- and three-key objects.
This prevents unbounded growth of prefixed keys that could indicate a bug or an injection attempt. Combined with patternProperties, you get both shape and cardinality guarantees declaratively.
schema = {"type": "object", "minProperties": 2, "maxProperties": 3}
print(list(Draft202012Validator(schema).iter_errors({}))) # 1 error
print(list(Draft202012Validator(schema).iter_errors({"a": 0}))) # 1 error
print(list(Draft202012Validator(schema).iter_errors({"a": 0, "b": 1}))) # []
print(list(Draft202012Validator(schema).iter_errors({"a":0,"b":1,"c":2,"d":3}))) # 1 errorApplicability limits and when to fall back to programmatic checks
patternProperties cannot express inter-key relationships such as: if key X exists then key Y must also exist with a matching value. Beyond what if/then covers with fixed discriminators, arbitrary cross-key logic requires a programmatic post-validation step.
Regex matching in patternProperties is case-sensitive and does not support Unicode property escapes in most validator implementations. The Python json module itself performs no schema validation, so a separate library such as jsonschema (version 4.0 or later for unevaluatedProperties support) is always required. For highly irregular key sets that do not follow a naming convention, a manual validation function remains simpler than an unwieldy schema.
The jsonschema library is not part of the standard library. Install it with: pip install jsonschema. For draft 2020-12 support including unevaluatedProperties, ensure jsonschema 4.0+ and optionally install jsonschema[format] for format validation.
import json
from jsonschema import Draft202012Validator
# Demonstrating a case where patternProperties alone is insufficient:
# "If S_owner exists, then I_owner_id must also exist" cannot be
# expressed declaratively. A post-validation check is needed.
def cross_key_check(obj):
if "S_owner" in obj and "I_owner_id" not in obj:
return ["S_owner present but I_owner_id missing"]
return []
payload = json.loads('{"S_owner": "alice", "source": "web", "url": "x"}')
print(cross_key_check(payload)) # ['S_owner present but I_owner_id missing']Things to check
- patternProperties regexes must be anchored with ^ and $ to avoid unintended substring matches on longer key names.
- unevaluatedProperties:false requires draft 2019-09 or later; older drafts silently ignore it, leaving additionalProperties as the only closure mechanism.
- The if subschema must include required for the discriminator key; otherwise an absent key trivially passes the properties check and then fires unexpectedly.
- additionalProperties only recognizes properties in its own subschema, not those in sibling subschemas reached through allOf or if/then.
- The Python json module performs zero schema validation; it only encodes and decodes, so jsonschema or an equivalent library is always required.
Where this applies
patternProperties cannot express relationships between two different dynamic keys such as matching pairs. Regex in patternProperties is not case-insensitive by default and does not support Unicode property classes in most validator implementations. The Python json module performs zero schema validation; it only encodes and decodes, so a separate validator is always required. unevaluatedProperties requires JSON Schema draft 2019-09 or later; older drafts must rely on additionalProperties with manual property enumeration in every subschema. For highly irregular key sets that do not follow a naming convention, a manual validation function remains simpler than an unwieldy schema.