Python-正在验证架构,试图需要一个字段



大家好!我感谢你的帮助。这是我第一次创建模式,它涉及航班数据,但我遇到了多个错误,因为在一些记录中,它不涉及特定的字段(在本例中,是dst_airport(。

以下是我包含的内容:

"dst_airport": {
"type": "object",
"properties": {
"airport_id": {
"type": "number"
},
"name": {
"type": "string"
},
"city": {
"type": "string"
},
"country": {
"type": "string"
},
"iata": {
"type": "string"
},
"iaco": {
"type": "string"
},
"latitude": {
"type": "number"
},
"longitude": {
"type": "number"
},
"altitude": {
"type": "number"
},
"timezone": {
"type": "number"
},
"dst": {
"type": "string"
},
"tz_id": {
"type": "string"
},
"type": {
"type": "string"
},
"source": {
"type": "string"
},
"anyOf": [
{
"required": [
"dst_airport"
]
}
]
}
}

我添加了我在网上找到的任何部分,试图修复它,但我认为它实际上没有任何作用。

有人能伸出援手吗?谢谢

required应与定义它们的properties处于同一级别。示例:

import jsonschema
schema = {
"type": "object",
"properties": {
"src_airport": {
"type": "object",
"properties": {
"airport_id": {"type": "number"}
}
},
"dst_airport": {
"type": "object",
"properties": {
"airport_id": {"type": "number"}
}
},
},
"required": [
"src_airport",
# do not put `dst_airport` here, meaning it is optional
]
}
example1 = {
"src_airport": {"airport_id": 1},
"dst_airport": {"airport_id": 2}
}
example2 = {
"src_airport": {"airport_id": 1},
# "dst_airport": {"airport_id": 2}
}
example3 = {
# "src_airport": {"airport_id": 1},
"dst_airport": {"airport_id": 2}
}
try:
jsonschema.validate(example1, schema=schema)
except jsonschema.exceptions.ValidationError:
print("example1: fail")
else:
print("example1: pass")
try:
jsonschema.validate(example2, schema=schema)
except jsonschema.exceptions.ValidationError:
print("example2: fail")
else:
print("example2: pass")
try:
jsonschema.validate(example3, schema=schema)
except jsonschema.exceptions.ValidationError:
print("example3: fail")
else:
print("example3: pass")

我也被jsonschema语法弄糊涂了。

相关内容

  • 没有找到相关文章