首页 文章

为什么json schema不验证在required属性中定义的定义

提问于
浏览
0

我正在尝试创建一个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"]
};

以下架构有效,即使它缺少"raw"属性: { "type" : "Literal" }

谢谢

1 回答

  • 2

    JSON Schema规范中没有关键字 content .

    一旦在根模式中声明了 "type":"object" ,就不需要在子模式中再次执行它 .

    为了将对象 type 枚举值与关联的扩展定义组合,您需要 allOf keyword .

    同样在定义中如果使用 "additionalProperties": false ,则必须列出对象的所有属性(请参阅 "type": {} ) . 对于先前定义/验证的属性,您可以使用许可模式: {}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"]
    }
    

相关问题