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

JSON Schema类型声明及多Schema按属性选择校验方法问询

JSON Schema 常见问题解答

嗨,咱们逐个拆解你的两个JSON Schema问题:

1. 如何在JSON Schema中声明JSON的类型?

在JSON Schema里,最基础的类型声明就是用type关键字,它既可以指定单个类型,也可以用数组指定多个允许的类型:

  • 单个类型示例:比如要校验一个字符串类型的JSON值,Schema可以这么写
{
  "type": "string"
}
  • 多类型示例:如果允许值是字符串或者数字(比如用户输入可以是文本格式的数字或纯数字),就用数组声明多个类型
{
  "type": ["string", "number"]
}

官方支持的基础类型包括:string、number、integer、boolean、array、object、null。如果需要更复杂的类型组合,还可以结合allOf、anyOf这些关键字,但type是最核心的类型声明方式。

2. 如何根据属性选择对应的Schema进行校验?

这个需求完全可行,而且是JSON Schema中非常常用的多态校验场景,专门用来处理不同类型的对象需要不同校验规则的情况。咱们可以用if/then/else关键字,或者oneOf来实现你说的「根据type属性选择对应Schema」的需求:

方式一:用if/then/else实现双向匹配

适合只有两种类型的场景,逻辑清晰:

{
  "type": "object",
  // 先声明公共的type属性规则
  "properties": {
    "type": { "type": "string", "enum": ["type1", "type2"] }
  },
  "required": ["type"],
  // 当type为type1时,应用then里的专属校验规则
  "if": {
    "properties": { "type": { "const": "type1" } },
    "required": ["type"]
  },
  "then": {
    "properties": {
      "type": {}, // 继承公共规则
      "field1": { "type": "string" } // type1专属的必填字段
    },
    "required": ["field1"]
  },
  // 否则(即type为type2),应用else里的规则
  "else": {
    "properties": {
      "type": {},
      "field2": { "type": "number" } // type2专属的必填字段
    },
    "required": ["field2"]
  }
}

方式二:用oneOf实现多类型匹配

如果后续要扩展更多类型(比如type3、type4),oneOf会更灵活,每个子Schema都明确绑定对应的type值:

{
  "type": "object",
  "oneOf": [
    {
      "properties": {
        "type": { "const": "type1" },
        "field1": { "type": "string" }
      },
      "required": ["type", "field1"]
    },
    {
      "properties": {
        "type": { "const": "type2" },
        "field2": { "type": "number" }
      },
      "required": ["type", "field2"]
    }
  ]
}

这两种方式都能让校验器自动根据type属性的值选择对应的Schema进行校验,完全满足你的需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:37:57