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

编写JSON Schema遇value类型切换及数组长度可变问题求助

修正后的JSON Schema实现

针对你提到的两个问题,这里是覆盖所有情况的JSON Schema:

{
  "type": "array",
  "minItems": 1,
  "maxItems": 4,
  "items": {
    "type": "object",
    "properties": {
      "id": {
        "type": "string"
      },
      "value": {
        "type": "object",
        "oneOf": [
          {
            "properties": {
              "text": { "type": "string" }
            },
            "required": ["text"],
            "additionalProperties": false
          },
          {
            "properties": {
              "number": { "type": "string" }
            },
            "required": ["number"],
            "additionalProperties": false
          }
        ]
      },
      "idCustomField": {
        "type": "string"
      },
      "idModel": {
        "type": "string"
      },
      "modelType": {
        "type": "string"
      }
    },
    "required": ["id", "value", "idCustomField", "idModel", "modelType"],
    "additionalProperties": false
  }
}

关键修改说明

  • 数组长度限制:通过minItems: 1和maxItems: 4,确保数组元素数量在1到4个之间,匹配你的需求。
  • value字段的多类型支持:
    • 使用oneOf关键字定义value的两种合法结构:要么包含必填的text字符串字段,要么包含必填的number字符串字段。
    • 每个子结构中添加additionalProperties: false,避免value中出现text和number之外的多余属性,同时确保两个字段不会同时存在。
  • 全局字段约束:顶层对象添加additionalProperties: false,防止出现API返回数据之外的未知字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:25:28