JsonSchemaValidationError data schema_error ai_generated true

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 · Markdown 中文 · English
90%修复率
92%置信度
1证据数
2023-09-18首次发现

版本兼容性

版本状态引入弃用备注
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.

generic

官方文档

https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties

解决方案

  1. 在验证之前修改输入JSON以删除多余属性。对于Python:`import json; data = json.loads(input_string); for key in list(data.keys()): if key not in schema['properties']: del data[key];`
  2. 如果使用JSON Schema 2019-09或更高版本,使用'unevaluatedProperties: false'代替'additionalProperties: false'。这允许通过$ref或allOf定义的属性被正确评估。
  3. 将特定的额外属性添加到模式中,附带适当的类型和描述,或使用带类型约束的'additionalProperties':`"additionalProperties": {"type": "string"}` 以允许额外属性但强制其类型。

无效尝试

常见但无效的做法:

  1. 50% 失败

    This undermines the purpose of strict validation and may allow malicious or malformed data through.

  2. 60% 失败

    This is impractical for dynamic or extensible APIs; also, it does not catch typos or unintended properties.

  3. 40% 失败

    PatternProperties are evaluated independently of additionalProperties; if both are present, additionalProperties applies to properties not matching any pattern.