[英]How to validate a list of dictionaries using jsonschema with Python
我有一个这样的字典列表:
list_of_dictionaries = [{'key1': True}, {'key2': 0.2}]
我想使用 jsonschema package 来验证它。
我创建了这样的架构:
schema = {
"type": "array",
"items": {
"type": "object",
"properties": {
"key1": {
"type": "boolean"
},
"key2": {
"type": "number"
}
},
"required": ["enabled"]
}
}
但这对我的列表是不正确的,因为要使其正常工作,我的列表应该是这样的:
list_dict = [{'key1': True, 'key2': 0.5}]
如何创建正确的架构来验证我的列表? 先感谢您。
我认为您可能想要使用oneOf
构造。 基本上,您试图描述一个可以包含任意数量的两种不同类型对象的列表。
这是一个使用示例(对不起,我使用 YAML 来声明我的jsonschema):
type: array
items:
$ref: '#/defs/element'
$defs:
element:
type: object
oneOf:
- $ref: '#/$defs/foo'
- $ref: '#/$defs/bar'
foo:
type: object
properties:
key1:
type: boolean
required:
- key1
bar:
type: object
properties:
key2:
type: boolean
required:
- key2
还有可能对您有用的anyOf
和allOf
组合器。 查看jsonschema 关于组合的文档以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.