JSON 任何属性的架构

JSON schema for anyOf properties

以一种非常简化的形式,我想定义一个 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。正确的定义方式是什么?

右边第一个属性"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}