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

JSON Schema校验未强制类型 如何约束show字段为布尔值

问题原因

你写的JSON Schema中,definitions 区块的作用是存储可复用的规则片段,本身不会自动对父级Schema生效,必须通过$ref主动引用才会触发校验,所以你定义的show为布尔类型的规则实际未生效,才会出现字符串类型的show也能正常存入的问题。
另外你没有给数组项显式指定"type": "object",也存在非对象类型的数组项被误存的隐患。

修正后的Schema(推荐写法,无需使用definitions)
{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "name": { "type": "string" },
      "show": { "type": "boolean" }
    },
    "required": ["name", "show"],
    "additionalProperties": false
  }
}

说明:additionalProperties 为可选配置,开启后会禁止数组项出现name、show之外的额外属性,可根据你的需求决定是否保留。

如果你确实需要保留definitions做规则复用,可采用如下写法
{
  "type": "array",
  "items": {
    "type": "object",
    "definitions": {
      "nameRule": { "type": "string" },
      "showRule": { "type": "boolean" }
    },
    "properties": {
      "name": { "$ref": "#/items/definitions/nameRule" },
      "show": { "$ref": "#/items/definitions/showRule" }
    },
    "required": ["name", "show"]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:36:02