You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写JSON Schema校验任意层级非空的field_name属性

Fixing JSON Schema to Validate 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:

  1. Checks if an object has a field_name property—if it does, enforce it’s a non-empty string.
  2. 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 with minLength: 1
      • Uses additionalProperties to apply the same recursive check to every value in the object (so nested objects get validated too)
    • For arrays:
      • Applies the recursive check to every item in the array (so objects inside arrays are scanned for field_name)
  • allOf at the root: Combines your original required fields rule with the new recursive check, ensuring both your top-level requirements and global field_name validation 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:59:18