【问题标题】:JSON schema for anyOf propertiesanyOf 属性的 JSON 模式
【发布时间】:2021-10-26 21:11:44
【问题描述】:

我想以一种非常简化的形式定义一个 JSON 模式,以允许

{ "a" : 1 }

{ "a" : {} }

但不是

{ "a" : 1, "b" : true }

而不是

{ "a" : true }

我想出了以下内容。

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "additionalProperties" : false,
  "anyOf" : [
    {
      "properties" : {
        "a" : {"type":"object"}
      }
    },
    {
      "properties" : {
        "a" : {"type":"integer"}
      }
    }
  ],
  "reqired" : ["a"]
}

但是,根据https://www.jsonschemavalidator.net/,除非我删除我绝对想要的"additionalProperties" : false,否则这是行不通的。什么是正确的定义方式?

【问题讨论】:

    标签: json schema


    【解决方案1】:

    首先属性"reqired" 是错误的,它应该是"required"

    此外,当您定义属性的类型时,您可以一次指定一个或多个类型:

    {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "type": "object",
        "additionalProperties": false,
        "properties": {
            "a": {
                "type": ["integer", "object"]
            }
        },
        "required": ["a"]
    }
    

    如果属性 a 是一个对象并且您想要特定的内容,您还可以添加额外的定义:

    {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "type": "object",
        "additionalProperties": false,
        "properties": {
            "a": {
                "type": ["integer", "object"],
                "properties": {
                    "b": {
                        "type": "integer"
                    }
                },
                "required": ["b"]
            }
        },
        "required": ["a"]
    }
    

    因此,如果您使用https://www.jsonschemavalidator.net/ 来验证您的架构,您将获得以下通过:

    {"a": 1} {"a": {"b": 1}}

    但这会失败: {"a": 1, "b": 1} {"a": {"b": 1}, "c":1}

    【讨论】:

      猜你喜欢
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      • 2020-02-03
      • 1970-01-01
      • 2015-04-26
      • 2019-03-21
      • 2016-04-23
      相关资源
      最近更新 更多