2

我有一个这样的字典列表:

list_of_dictionaries = [{'key1': True}, {'key2': 0.2}]

我想使用 jsonschema 包来验证它。

我创建了这样的架构:

schema = {
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "key1": {
                "type": "boolean"
            },
            "key2": {
                "type": "number"
            }
        },
        "required": ["enabled"]
    }
}

但这对我的列表是不正确的,因为要使其正常工作,我的列表应该是这样的:

list_dict = [{'key1': True, 'key2': 0.5}]

如何创建正确的架构来验证我的列表?先感谢您。

4

1 回答 1

5

我认为您可能想要使用该oneOf构造。基本上,您试图描述一个可以包含任意数量的两种不同类型对象的列表。

这是一个使用示例:

{
  "type": "array",
  "items": {
    "$ref": "#/defs/element"
  },
  "$defs": {
    "element": {
      "type": "object",
      "oneOf": [
        {
          "$ref": "#/$defs/foo"
        },
        {
          "$ref": "#/$defs/bar"
        }
      ]
    },
    "foo": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "key1": {
          "type": "boolean"
        }
      },
      "required": [
        "key1"
      ]
    },
    "bar": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "key2": {
          "type": "boolean"
        }
      },
      "required": [
        "key2"
      ]
    }
  }
}

还有一些可能对您有用的组合器anyOfallOf查看jsonschema 关于组合的文档以获取更多信息。

于 2022-02-01T19:30:47.097 回答