如何修改JSON Schema以限制depends_on数组仅包含根对象的键名(排除所属父键)
Solution to Restrict
depends_on to Valid Root Keys (Excluding Parent Key) To enforce that each depends_on array only contains existing root keys and excludes its parent key, we'll modify the schema using JSON Schema Draft 07+ features (specifically the $data keyword, which is widely supported in libraries like AJV).
Modified Schema
{ "type": "object", "patternProperties": { "^.+$": { "type": "object", "properties": { "depends_on": { "type": "array", "items": { "type": "string", // Prevent the array from including the parent key "not": { "const": {"$data": "1"} }, // Ensure each item is a valid key present at the root "allOf": [ { "$data": "#", "required": [{"$data": "0"}] } ] } } }, "additionalProperties": false } }, "additionalProperties": false }
Key Changes Explained
- Excluding the Parent Key: The
not: {const: {"$data": "1"}}rule uses$data: "1"to reference the key of the parent object (the root-level key that owns thisdepends_onarray). This ensures the array can't include its own parent key. - Validating Root Keys: The
$data: "#"references the entire root JSON object. We then applyrequired: [{"$data": "0"}], where$data: "0"points to the current item in thedepends_onarray. This guarantees the root object has a key matching the item. - Preventing Extra Properties: The
additionalProperties: falseconstraints (at both levels) ensure no unexpected properties are added to the objects under root keys or thedepends_oncontainer.
Fallback for Older JSON Schema Drafts
If your implementation doesn't support $data (common in older drafts), you can only enforce this with static keys using enum. This is less flexible but works for fixed root keys:
{ "type": "object", "properties": { "foo": {"type": "object", "properties": {"depends_on": {"type": "array", "items": {"enum": []}}}}, "bar": {"type": "object", "properties": {"depends_on": {"type": "array", "items": {"enum": ["foo"]}}}} }, "required": ["foo", "bar"], "additionalProperties": false }
内容的提问来源于stack exchange,提问作者Mohammad Reza Bozorgmehr
相关产品推荐
相关产品推荐

