![](/img/trans.png)
[英]How to validate a list of dictionaries using jsonschema with Python
[英]How to validate an array of custom objects with jsonschema in Python
我的每个数据点都有这个主要模式:
data_schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"city": {"type": "string"},
"distance": {"type": "number"},
"extrovert": {"type": "boolean"},
"favorite_temperature": {"type": "number"},
},
}
然后我期望这些称为data
的列表。 我想验证所有这些,如何使用jsonschema
模块来完成?
这是我失败的尝试,因为它似乎无法识别数组架构中的自定义主架构:
from jsonschema import validate
from time import time
from faker import Faker
import numpy as np
Faker.seed(0)
fake = Faker()
def create_data(x: int):
'''Create fake data'''
# dictionary
data = []
for i in range(0, x):
data_i = {}
data_i['name']= fake.name()
data_i['city']= fake.city()
data_i['distance'] = np.random.randint(1,5)
data_i['extrovert'] = fake.pybool()
data_i['favorite_temperature'] = fake.pyfloat(left_digits=2,
right_digits=2)
data.append(data_i)
return data
data = create_data(3)
t0 = time()
data_schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"city": {"type": "string"},
"distance": {"type": "number"},
"extrovert": {"type": "boolean"},
"favorite_temperature": {"type": "number"},
},
}
list_schema = {
"type": "array",
"items": {"type": data_schema},
}
validated_data = validate(instance=data, schema=list_schema)
t1 = time()
duration = t1 - t0
print(f"Json_Schema validation lasted: {duration} sec")
这是我得到的错误:
jsonschema.exceptions.SchemaError: {'type': 'object', 'properties': {'name': {'type': 'string'}, 'city': {'type': 'string'}, 'closeness (1-5)': {'type': 'number'}, 'extrovert': {'type': 'boolean'}, 'favorite_temperature': {'type': 'number'}}} is not valid under any of the given schemas
"items": {"type": data_schema}
应该只是"items": data_schema
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.