如何编写JSON Schema校验任意层级非空的field_name属性
field_name at All Levels Ah, I see the issue here—your current schema uses patternProperties, but that only validates keys at the current level of the object it's applied to. It doesn't recursively check nested objects or arrays, which is why empty field_name values deeper in your JSON aren't being caught. To validate this property everywhere in your structure, you need a recursive schema that traverses every object and array in the JSON.
Here’s how to fix it:
The Core Idea
Define a reusable schema fragment that:
- Checks if an object has a
field_nameproperty—if it does, enforce it’s a non-empty string. - Recursively applies this check to all nested objects (including those inside arrays).
Corrected JSON Schema
{ "$schema": "http://json-schema.org/schema#", "title": "Metadata Model", "type": "object", "required": ["name", "abbreviation", "version", "releaseDate", "scope", "content"], "allOf": [ { "$ref": "#/$defs/recursiveFieldCheck" } ], "$defs": { "recursiveFieldCheck": { "type": ["object", "array"], "anyOf": [ // Handle objects: check field_name (if present) and recurse into properties { "type": "object", "properties": { "field_name": { "type": "string", "minLength": 1, "description": "Must be a non-empty string" } }, "additionalProperties": { "$ref": "#/$defs/recursiveFieldCheck" } }, // Handle arrays: recurse into each item { "type": "array", "items": { "$ref": "#/$defs/recursiveFieldCheck" } } ] } } }
Breakdown of Changes
$defs/recursiveFieldCheck: This is the reusable recursive rule. It targets both objects and arrays:- For objects:
- Validates
field_name(if present) is a string withminLength: 1 - Uses
additionalPropertiesto apply the same recursive check to every value in the object (so nested objects get validated too)
- Validates
- For arrays:
- Applies the recursive check to every item in the array (so objects inside arrays are scanned for
field_name)
- Applies the recursive check to every item in the array (so objects inside arrays are scanned for
- For objects:
allOfat the root: Combines your original required fields rule with the new recursive check, ensuring both your top-level requirements and globalfield_namevalidation are enforced.
Why Your Original Schema Failed
patternProperties only operates on the keys of the object it’s attached to. It doesn’t look inside nested objects, arrays, or any deeper structures. The recursive approach fixes this by explicitly traversing every part of the JSON.
内容的提问来源于stack exchange,提问作者stopopol

