Cla*_*one 2 python jsonschema python-jsonschema
我有一个这样的字典列表:
list_of_dictionaries = [{'key1': True}, {'key2': 0.2}]
Run Code Online (Sandbox Code Playgroud)
我想使用 jsonschema 包来验证它。
我创建了这样的架构:
schema = {
"type": "array",
"items": {
"type": "object",
"properties": {
"key1": {
"type": "boolean"
},
"key2": {
"type": "number"
}
},
"required": ["enabled"]
}
}
Run Code Online (Sandbox Code Playgroud)
但这对于我的列表来说是不正确的,因为要使其正常工作,我的列表应该是这样的:
list_dict = [{'key1': True, 'key2': 0.5}]
Run Code Online (Sandbox Code Playgroud)
如何创建正确的架构来验证我的列表?先感谢您。
我想你可能想使用这个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"
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
还有anyOf一些allOf组合器可能对您有用。查看jsonschema 有关组合的文档以获取更多信息。