【问题标题】:Json Schema matching with 'anyOf'与“anyOf”匹配的 Json Schema
【发布时间】:2020-10-01 23:57:47
【问题描述】:

我希望能够管理一个“对象”的 json 数组,其中每个对象都有一个类型和属性,如果对象中缺少强制属性,则会出现架构错误。

这是我尝试这样做(不包括数组部分)声明两种对象类型并说 json 中的对象可以是这两种类型中的任何一种:

{
  'definitions': 
  {
    'typeone': 
    {
      'type': 'object',
      'properties': 
      {
        'xtype': {'type':'string', 'const':'typeone'},
        'num' :  {'type':'number'}
      },
      'required':['xtype', 'num'],
      'additionalProperties':false
    },
    'typetwo': 
    {
      'type': 'object',
      'properties': 
      {
        'xtype': {'type':'string', 'const':'typetwo'},
        'str' :  {'type':'string'}
      },
      'required':['xtype', 'str'],
      'additionalProperties':false
    }
  },
  'anyOf':
  [
     { '$ref': '#/definitions/typeone' },
     { '$ref': '#/definitions/typetwo' },
  ]
}

但是,如果我输入 json,它会失败,因为这样的对象缺少强制属性:

{
  'xtype': 'typeone'
}

...JSON does not match any schemas from 'anyOf'. 出现错误 - 我可以看出原因是它不知道尝试匹配 xtype,而只是认为 xtype 的 'typeone' 无效并查看其他人。

有没有更好的方法来执行anyOf,它将基于一个属性值(如“开关”)进行硬匹配,然后给出关于缺少该对象类型的其他强制属性的错误?

【问题讨论】:

  • 否,但 JSON Schema 草案 2019-09 有标准化输出,然后您可以使用它来创建错误消息。对不起。

标签: json jsonschema


【解决方案1】:

它变得更加冗长,但您可以使用if/then 来切换基于“xtype”属性的验证。

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "allOf": [
    {
      "if": {
        "type": "object",
        "properties": {
          "xtype": { "const": "typeone" }
        },
        "required": ["xtype"]
      },
      "then": { "$ref": "#/definitions/typeone" }
    },
    {
      "if": {
        "type": "object",
        "properties": {
          "xtype": { "const": "typetwo" }
        },
        "required": ["xtype"]
      },
      "then": { "$ref": "#/definitions/typetwo" }
    }
  ],
  "definitions": {
    "typeone": {
      "type": "object",
      "properties": {
        "xtype": {},
        "num": { "type": "number" }
      },
      "required": ["num"],
      "additionalProperties": false
    },
    "typetwo": {
      "type": "object",
      "properties": {
        "xtype": {},
        "str": { "type": "string" }
      },
      "required": ["str"],
      "additionalProperties": false
    }
  }
}

只需对模型稍作改动,您就可以使用dependencies 来获得更简单、更简洁的架构。您可以拥有一个与类型名称相对应的属性,而不是拥有一个“xtytpe”​​属性。例如,{ "typeone": true }

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "dependencies": {
    "typeone": {
      "type": "object",
      "properties": {
        "typeone": {},
        "num": { "type": "number" }
      },
      "required": ["num"],
      "additionalProperties": false
    },
    "typetwo": {
      "type": "object",
      "properties": {
        "typetwo": {},
        "str": { "type": "string" }
      },
      "required": ["str"],
      "additionalProperties": false
    }
  }
}

【讨论】:

  • 谢谢你的想法,我没想到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 2020-03-27
  • 1970-01-01
  • 2022-10-04
  • 2014-08-12
相关资源
最近更新 更多