如何为仅包含可选元素的文档编写有效的JSON Schema?并修改指定Schema使空JSON配置文件验证通过
To allow an empty JSON document (like {}) to pass validation with your schema, you actually might not need to make any changes—let me break down why, plus cover explicit tweaks you can make for clarity or edge cases:
Why your current schema already permits empty JSON
- Your root schema defines an
objectwith no properties marked as required (there’s norequiredarray at the root level). In JSON Schema, all properties are optional by default unless explicitly listed inrequired. - The
additionalProperties: falserule only blocks properties that aren’t in your allowedpropertieslist. Since an empty document has no properties at all, this rule doesn’t trigger a failure. - Objects default to
minProperties: 0, so an empty object is inherently valid.
Explicit tweak for clarity (optional)
If you want to make this allowance explicit (to avoid confusion for future maintainers, or if your validator has unexpected behavior), add minProperties: 0 to the root object schema. This doesn’t change validation logic, but it makes your intent clear:
{ "$id": "https://snafu.com/api/service/publishing-mechanism/config-delta/1.0.0", "$schema": "https://json-schema.org/draft/2019-09/schema", "description": "....", "type": "object", "additionalProperties": false, "minProperties": 0, // Explicitly allow empty root objects "properties": { "plans": { "type": "object", "additionalProperties": false, "minProperties": 1, "patternProperties": { "^.*$": { "type": "object", "additionalProperties": false, "properties": { "description": {"type": "string"}, "validation": {"type": "string", "enum": ["auto", "manual"]}, "security": {"type": "string", "enum": ["api_key"]} } } } } } }
Bonus: Allowing empty plans objects (if needed)
If you also want to accept documents like {"plans": {}} (empty plans object), you’d need to remove the minProperties: 1 line from the plans schema. But this is separate from your original question about empty JSON documents.
内容的提问来源于stack exchange,提问作者Oliver

