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

如何用JSON Schema确保active_choice取值为possible_choices数组元素

实现动态枚举:限制active_choice只能取自possible_choices数组

给定示例JSON:

{"possible_choices": ["one", "two", "three"],"active_choice": "two"}

要确保active_choice的取值必须是possible_choices数组中的某一项,可以借助JSON Schema的$data关键字(仅支持draft-07及以上版本)实现动态枚举效果,具体Schema如下:

{
  "type": "object",
  "properties": {
    "possible_choices": {
      "type": "array",
      "items": { "type": "string" },
      "minItems": 1
    },
    "active_choice": {
      "type": "string",
      "enum": { "$data": "/possible_choices" }
    }
  },
  "required": ["possible_choices", "active_choice"]
}

关键说明:

  • possible_choices被定义为至少包含一个字符串元素的数组,保证有可用的枚举选项。
  • active_choice的enum字段通过$data引用了/possible_choices路径对应的数组值,相当于把数组内容作为动态枚举列表,强制active_choice的取值必须是该数组中的某一项。
  • 如果使用draft-07以下的JSON Schema版本,无法实现这种动态关联,只能手动写死固定的枚举值。

验证效果:

  • 当active_choice取值为"one"、"two"或"three"时,验证通过。
  • 当active_choice取值为"four"这类不在possible_choices中的值时,验证失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 07:45:15