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

求助:构建符合User接口规范的React应用JSON Schema

解决React应用中User接口对应的JSON Schema校验问题

针对你给出的TypeScript User接口,以下是符合要求的JSON Schema,能有效拦截非法属性并满足校验规则:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "User",
  "required": ["userName", "systemAlerts", "loginAlerts"],
  "properties": {
    "userName": {
      "type": "string"
    },
    "systemAlerts": {
      "type": "object",
      "title": "SystemAlerts",
      "additionalProperties": false,
      "properties": {
        "alert1": {
          "type": ["string", "null"]
        },
        "alert2": {
          "type": ["string", "null"]
        }
      }
    },
    "loginAlerts": {
      "type": "object",
      "title": "LoginAlerts",
      "additionalProperties": false,
      "properties": {
        "alert1": {
          "type": "object",
          "title": "LoginAlertItem",
          "additionalProperties": false,
          "required": ["code1", "code2"],
          "properties": {
            "code1": {
              "type": ["string", "null"]
            },
            "code2": {
              "type": ["string", "null"]
            }
          }
        },
        "alert2": {
          "type": "object",
          "title": "LoginAlertItem",
          "additionalProperties": false,
          "required": ["code1", "code2"],
          "properties": {
            "code1": {
              "type": ["string", "null"]
            },
            "code2": {
              "type": ["string", "null"]
            }
          }
        }
      }
    }
  },
  "additionalProperties": false
}

关键规则说明

  • 禁止非法属性:所有对象层级都设置了additionalProperties: false,这是拦截alert11、code11这类未定义属性的核心。只要不在properties里声明的属性,都会被判定为无效。
  • systemAlerts规则:必填对象,可空(无任何属性),仅允许包含alert1、alert2,二者都是可选的字符串或null。
  • loginAlerts规则:必填对象,可空;若存在alert1或alert2,则这两个属性必须是包含code1、code2的对象(code1和code2为必填的字符串或null),且alert1/alert2内部也不允许有其他非法属性。

之前的问题根源是未启用additionalProperties: false,JSON Schema默认允许额外属性,所以需要显式禁用才能拦截非法字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:22:16