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

JSON Schema验证异常求助:仅首个patternProperties规则生效

JSON Schema Draft-04验证异常排查:patternProperties重复键与类型不匹配问题

核心问题1:patternProperties重复键导致规则覆盖

你在Specifics的patternProperties里重复定义了^.*$这个正则键——JSON对象不允许重复键,后定义的规则会被前一个覆盖,所以只有第一个数组类型的规则生效,字符串类型的规则完全没起作用。

要实现"任意属性要么是带布尔属性对象的数组,要么是字符串"的需求,需要用oneOf把两种规则合并到同一个^.*$键下,让每个属性值满足其中一种规则即可。

核心问题2:待验证JSON的类型不匹配

你的Schema定义CategoryID为integer类型,但待验证的JSON里CategoryID是字符串"2312312",这也会触发验证失败。


修正后的Schema代码

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "PrimaryCategory": {
      "type": "object",
      "properties": {
        "CategoryID": {
          "type": "integer"
        },
        "Name": {
          "type": "string"
        },
        "Specifics": {
          "type": "object",
          "patternProperties": {
            "^.*$": {
              "oneOf": [
                {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "patternProperties": {
                      "^.*$": {
                        "type": "boolean"
                      }
                    }
                  }
                },
                {
                  "type": "string"
                }
              ]
            }
          }
        }
      },
      "required": [
        "CategoryID",
        "Name"
      ]
    }
  },
  "required": [
    "PrimaryCategory"
  ]
}

修正后的待验证JSON示例

{
  "PrimaryCategory": {
    "CategoryID": 2312312,
    "Name": "category",
    "Specifics": {
      "field1": [
          {"bool1": true},
          {"bool2": false}
      ],
      "field2": "value1",
      "field3": "value2"
    }
  }
}

内容的提问来源于stack exchange,提问作者blob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:03:20