繁体   English   中英

如何在 Python 中使用 jsonschema 验证自定义对象数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM