首页 > 解决方案 > 为什么 json 模式不验证必需属性中定义的定义

问题描述

我正在尝试创建一个 json 模式,该模式根据对象的类型对其进行验证。它选择正确的定义,但是,它不会验证所选定义中的必需属性。这是我正在尝试的 json 模式:

{
    "$schema": "http://json-schema.org/draft-07/schema#",

    "definitions": {
        "literal": {
            "type": "object",
            "properties": {
                "raw": { "type": "string" }
            },
            "required": ["raw"],
            "additionalProperties": false
        },
        "identifier": {
            "type": "object",
            "properties": {
                "name": { "type": "string" }
            },
            "required": ["name"],
            "additionalProperties": false
        }
    },

    "type": "object",
    "oneOf": [
        {
            "type": "object",
            "properties": {
                "type": {
                    "enum": ["Literal"]
                },
                "content": { "$ref": "#/definitions/literal" }
            }
        },
        {
            "type": "object",
            "properties": {
                "type": {
                    "enum": ["Identifier"]
                },
                "content": { "$ref": "#/definitions/identifier" }
            }
        }
    ],
    "required": ["type"]
};

以下架构是有效的,即使它缺少“原始”属性: { "type" : "Literal" }

谢谢

标签: jsonjsonschema

解决方案


JSON Schema 规范中没有关键字content

在根模式中断言"type":"object"后,无需在子模式中再次执行此操作。

为了将对象type枚举值与关联的扩展定义结合起来,您需要allOf关键字。

同样在定义中,如果您使用"additionalProperties": false,则必须列出对象的所有属性(请参阅 参考资料"type": {})。对于先前定义/验证的属性,您可以只使用 permissive schema:{}true.

{
  "$schema": "http://json-schema.org/draft-07/schema#",

  "definitions": {
    "literal": {
      "properties": {
        "type": {},
        "raw": { "type": "string" }
      },
      "required": ["raw"],
      "additionalProperties": false
    },
    "identifier": {
      "properties": {
        "type": {},
        "name": { "type": "string" }
      },
      "required": ["name"],
      "additionalProperties": false
    }
  },

  "type": "object",
  "oneOf": [
    {
      "allOf": [
        {
          "properties": {
            "type": {
              "enum": ["Literal"]
            }
          }
        },
        {"$ref": "#/definitions/literal"}
      ]
    },
    {
      "allOf": [
        {
          "properties": {
            "type": {
              "enum": ["Identifier"]
            }
          }
        },
        {"$ref": "#/definitions/identifier" }
      ]
    }
  ],
  "required": ["type"]
}

推荐阅读