我有一个JSON模式,我想使用python和jsonschema模块来验证一些数据。但是,这不能完全按预期工作,因为某些接受的数据似乎根本无效(对我和我的应用目的而言)。可悲的是,提供了模式,所以我不能更改模式本身-至少不能手动更改。
这是架构的简化版本(以下代码中的“ schema.json”):
{
"type": "object",
"allOf": [
{
"type": "object",
"allOf": [
{
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
}
}
},
{
"type": "object",
"properties": {
"language": {
"type": "integer"
}
}
}
]
},
{
"type": "object",
"properties": {
"addressArray": {
"type": "array",
"items": {
"type": "object",
"properties": {
"streetNumber": {
"type": "string"
},
"street": {
"type": "string"
},
"city": {
"type": "string"
}
}
}
}
}
}
]
}
这是一个有效实例的示例(以下代码中的“ person.json”):
{
"firstName": "Sherlock",
"lastName": "Holmes",
"language": 1,
"addresses": [
{
"streetNumber": "221B",
"street": "Baker Street",
"city": "London"
}
]
}
这是应视为无效的示例(以下代码中的“ no_person.json”):
{
"name": "eggs",
"colour": "white"
}
这是我用于验证的代码:
from json import load
from jsonschema import Draft7Validator, exceptions
with open('schema.json') as f:
schema = load(f)
with open('person.json') as f:
person = load(f)
with open('no_person.json') as f:
no_person = load(f)
validator = Draft7Validator(schema)
try:
validator.validate(person)
print("person.json is valid")
except exceptions.ValidationError:
print("person.json is invalid")
try:
validator.validate(no_person)
print("no_person.json is valid")
except exceptions.ValidationError:
print("no_person.json is invalid")
结果:
person.json is valid
no_person.json is valid
我希望no_person.json无效。仅成功验证诸如person.json之类的数据,该怎么办?非常感谢您的帮助,我对此很陌生(花了很长时间寻找答案)。
答案 0 :(得分:0)
这是工作模式,请注意“必填”(如果没有这样的键-如果没有得到该键,则将其跳过):
{
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"language": {
"type": "integer"
},
"addresses": {
"type": "array",
"items": {
"type": "object",
"properties": {
"streetNumber": {
"type": "string"
},
"street": {
"type": "string"
},
"city": {
"type": "string"
}
},
"required": [
"streetNumber",
"street",
"city"
]
}
}
},
"required": [
"firstName",
"lastName",
"language",
"addresses"
]
}
我有:
person.json is valid
no_person.json is invalid
如果您的响应结构最困难(对象阵列,其中包含对象等),请告诉我