使用patternProperties进行JSON Schema校验失效问题求助
Hey Klaus, let's break down why your patternProperties rule isn't enforcing the key format you expect—there are a few small but critical issues in your schema that are causing the problem:
1. You're missing additionalProperties: false for the falMedia object
When using patternProperties to define allowed key patterns, JSON Schema allows any extra keys that don't match the pattern by default (since additionalProperties defaults to true). To block non-matching keys, you need to explicitly set additionalProperties: false in the falMedia object schema. This tells the validator that only keys matching your regex are permitted.
2. additionalProperties is misplaced in the processedFile schema
In your current schema, you've nested additionalProperties: false inside the properties block of processedFile—this is incorrect. It should be at the same level as type and properties to take effect.
3. The title field in falMedia sub-objects doesn't allow null
Your schema defines "title": { "type": "string" }, but the first news item has title: null in its falMedia entries. This would cause a validation failure, so you need to update this to allow both string and null values, just like you did for the alternative field.
Corrected Schema
Here's the fixed version of your schema with all these issues addressed:
{ "$schema": "http://json-schema.org/draft-04/schema", "title": "FPÖ News", "description": "Schema for FPÖ News articles accessed by the mobile apps", "type": "array", "items": { "additionalProperties": false, "properties": { "bodytext": { "type": "string" }, "datetime": { "type": "string" }, "falMedia": { "anyOf": [ { "type": "object", "patternProperties": { "^[0-9abcde]*$": { "type": "object", "properties": { "alternative": { "type": ["null", "string"] }, "description": { "type": "string" }, "link": { "type": "string" }, "pid": { "type": "integer" }, "processedFile": { "type": "object", "properties": { "publicUrl": { "type": "string" } }, "additionalProperties": false }, "title": { "type": ["string", "null"] }, "uid": { "type": "integer" } }, "additionalProperties": false } }, "additionalProperties": false }, { "type": "array" } ] }, "falRelatedFiles": { "type": "array" }, "istopnews": { "type": "boolean" }, "pid": { "type": "integer" }, "teaser": { "type": ["string", "null"] }, "title": { "type": "string" }, "uid": { "type": "integer" } }, "required": [ "bodytext", "datetime", "istopnews", "pid", "teaser", "title", "uid" ] } }
How This Fixes Your Issue
- Now, if you use a falMedia key that doesn't match
^[0-9abcde]*$(like"invalid-key"), the validator will correctly reject the JSON becauseadditionalProperties: falseblocks unrecognized keys. - The
processedFileschema now properly enforces that only thepublicUrlfield is allowed. - The
titlefield in falMedia entries will acceptnullvalues, matching your sample JSON.
内容的提问来源于stack exchange,提问作者Klaus Hörmann-Engl

