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

如何配置含固定必填值且允许额外值的字符串数组JSON Schema

报错根因

报错是contains关键字用法错误导致的:

  • JSON Schema中contains是数组层级的校验关键字,不能写在items配置内部,且它的值必须是一个完整的Schema对象,作用是校验数组中是否至少存在一个元素匹配该Schema,不能直接传入值数组。
  • 原定义把contains写在items对象内,还直接赋值为["fk", "uid"]数组,Go语言的JSON Schema解析库预期contains字段是Schema对象类型,遇到数组就会抛出你看到的类型反序列化错误。
修复方法

要实现attributes数组必须固定包含"fk"、"uid"两个值,同时支持传入其他额外字符串的需求,正确的Schema配置需要满足几个规则:

  • 数组所有元素均为字符串类型
  • 数组至少包含一个值为"fk"的元素
  • 数组至少包含一个值为"uid"的元素
  • 保留原有的minItems: 2约束,两个必填值已经满足最小长度要求

修复后的完整Schema如下:

{
    "type": "object",
    "properties": {
        "campaignType": {
            "type": "string",
            "enum": ["export"]
        },
        "clientid": {
            "type": "integer",
            "minimum": 1
        },
        "select": {
            "type": "object",
            "minProperties": 1,
            "anyOf": [
                {"required": ["list"]},
                {"required": ["segment"]}
            ],
            "properties": {
                "list": {
                    "type": "array",
                    "items": {"type": "integer"}
                },
                "segment": {
                    "type": "array",
                    "items": {"type": "integer"}
                }
            }
        },
        "attributes": {
            "type": "array",
            "minItems": 2,
            "items": {"type": "string"},
            "allOf": [
                {"contains": {"const": "fk"}},
                {"contains": {"const": "uid"}}
            ]
        }
    },
    "required": ["campaignType", "clientid", "select", "attributes"]
}
校验效果说明
  • 你提供的测试数据{"campaignType":"export","clientid":107311,"select":{"segment":[30]},"attributes":["uid","fk", "att1"]}可以完全通过校验,不会再抛出解析错误
  • 如果attributes缺了"fk"或者"uid"任意一个值,会直接触发校验失败
  • 除了两个必填值外,传入任意数量的额外字符串元素都能正常通过
  • 如果数组里出现非字符串类型的元素,也会被items规则拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 07:39:19