JSON Schema验证失败:模式具有'additionalProperties: false'时不允许额外属性
JSON Schema validation fails: additional properties not allowed when schema has 'additionalProperties: false'
ID: data/json-schema-additional-properties-true
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| JSON Schema Draft-07+ | active | — | — | — |
| ajv 8.12+ | active | — | — | — |
| jsonschema 4.20+ | active | — | — | — |
| OpenAPI 3.0+ | active | — | — | — |
根因分析
JSON Schema显式设置'additionalProperties: false'以将对象限制为仅定义的属性,但输入JSON包含模式'properties'关键字中未列出的属性。
English
A JSON Schema explicitly sets 'additionalProperties: false' to restrict the object to only defined properties, but the input JSON contains properties not listed in the schema's 'properties' keyword.
官方文档
https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties解决方案
-
在验证之前修改输入JSON以删除多余属性。对于Python:`import json; data = json.loads(input_string); for key in list(data.keys()): if key not in schema['properties']: del data[key];`
-
如果使用JSON Schema 2019-09或更高版本,使用'unevaluatedProperties: false'代替'additionalProperties: false'。这允许通过$ref或allOf定义的属性被正确评估。
-
将特定的额外属性添加到模式中,附带适当的类型和描述,或使用带类型约束的'additionalProperties':`"additionalProperties": {"type": "string"}` 以允许额外属性但强制其类型。
无效尝试
常见但无效的做法:
-
50% 失败
This undermines the purpose of strict validation and may allow malicious or malformed data through.
-
60% 失败
This is impractical for dynamic or extensible APIs; also, it does not catch typos or unintended properties.
-
40% 失败
PatternProperties are evaluated independently of additionalProperties; if both are present, additionalProperties applies to properties not matching any pattern.