如何配置JSON Schema:无元素时不保留数组字段,禁用空对象数组
JSON Schema for Validating Quantity with Optional Non-Empty Modifiers
Got it, let's build the JSON Schema that fits your exact validation requirements. Here's a solution that covers all your cases, along with explanations of how each part works:
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "required": ["quantity"], "properties": { "quantity": { "type": "integer" }, "modifiers": { "type": "array", "items": { "type": "object", "minProperties": 1 }, "minItems": 1 } }, "oneOf": [ { "not": { "required": ["modifiers"] } }, { "required": ["modifiers"] } ], "additionalProperties": false }
Key Validation Logic Breakdown
Let's walk through why this schema works for your rules:
- Mandatory
quantityfield: Therequiredarray ensuresquantityis always present and typed as an integer. - Prevent unexpected fields:
additionalProperties: falseblocks any extra fields not defined in the schema, keeping your JSON structure strict. - Two mutually valid cases via
oneOf:- No
modifiersallowed: The firstoneOfrule usesnot: {required: ["modifiers"]}to enforce that if you don't intend to add modifiers, the field shouldn't exist at all. - Valid
modifiersrequired when present: The second rule makesmodifiersmandatory if it's going to be included, with these checks:modifiersmust be an array with at least one item (minItems: 1)- Every object in the
modifiersarray must have at least one key-value pair (minProperties: 1), which directly blocks empty objects like{}in the array.
- No
Test Cases
Let's verify against your examples:
Valid (no modifiers):
{"quantity": 3}Passes: No
modifiersfield, meets the firstoneOfcondition.Valid (with non-empty modifiers):
{"quantity": 3, "modifiers": [{"testing": "some data here"}]}Passes:
modifiersarray contains a non-empty object, meets the secondoneOfcondition.Invalid (empty modifier object):
{"quantity": 3, "modifiers": [{}]}Fails: The array item fails the
minProperties: 1check for modifier objects.
Additional invalid cases that get blocked:
- Empty
modifiersarray ({"quantity":3, "modifiers":[]}) modifiersas a non-array value ({"quantity":3, "modifiers": {}})- Extra fields not defined in the schema (
{"quantity":3, "extraField": "test"})
内容的提问来源于stack exchange,提问作者CyberMew
相关产品推荐
相关产品推荐

