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

如何在JSON Schema中定义符合指定Schema的预设可选对象属性?

解决方案

你可以用allOf关键字把枚举限制和schema验证结合起来,这样既要求值必须是枚举里的预设对象,又强制这些对象符合你定义的fruit schema规范。另外先纠正你现有schema里的一个错误:$defs.fruit中的properties应该是对象类型,不是数组,这是JSON Schema的语法要求。

具体实现步骤:

  • 先修正$defs里的fruit schema,把properties改成对象结构,确保它能正确验证水果对象的格式。
  • 使用allOf数组,同时包含enum(指定允许的预设对象)和$ref(引用fruit schema做格式验证)。这样枚举里的每个对象都会被自动校验是否符合fruit的规范,不符合的话整个schema会报错。

修正后的完整schema示例:

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "description": "this is my favorite fruit",
    "allOf": [
        {
            "enum": [
                {
                    "name": "apple",
                    "color": "red"
                },
                {
                    "name": "banana",
                    "color": "yellow"
                },
                {
                    "name": "oops, that's not a fruit",
                    "taste": "fantastic"
                }
            ]
        },
        {
            "$ref": "#/$defs/fruit"
        }
    ],
    "$defs": {
        "fruit": {
            "type": "object",
            "properties": {
                "name": {
                    "type": "string"
                },
                "color": {
                    "type": "string"
                }
            },
            "required": [
                "name",
                "color"
            ],
            "unevaluatedProperties": false
        }
    }
}

效果说明

  • 验证数据时,输入值必须是enum里的对象之一。
  • 同时enum里的每个对象都会被fruit schema校验:比如第三个对象缺少color属性、多了taste属性,会直接触发验证失败,能提前发现枚举里不符合规范的对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 07:12:33