简体   繁体   English

如何从架构中的json文件中获取缺少的字段,反之亦然

[英]How can I get missing fields from json file in schema and vice versa

I have installed jsonschema using pip install jsonschema . 我已经安装了jsonschema使用pip install jsonschema

from jsonschema import validate

schema_data = {
    "type" : "object",
    "properties" : {
        "price" : {"type" : "number"},
        "name" : {"type" : "string"},
        "additional" : {"type" : "number"},
        },
    }

json_data = {"name" : "Eggs", "price" : 34.99, "new": 90}

I am having above schema_data and json_data which is just validating the datatype. 我上面有schema_datajson_data ,它们只是验证数据类型。

Here additional is an extra field in schema_data which is absent in json_data , and new is present in json_data which is absent in schema_data . 下面additional是一个额外的领域schema_data这是在缺席json_data ,以及new出现在json_data这是不存在的schema_data

How can I list missing fields like additional is missing in json_data and new is missing in schema_data ? 如何列出json_data中缺少的additional字段以及json_data new丢失schema_data

In a JSON Schema, by default properties are not required , all that your schema does is state what type they must be if the property is present . 在JSON模式中,默认情况下不需要属性,您的模式所做的只是声明如果存在该属性它们必须是什么类型。 So for validation to flag that additional is missing, you need to mark that key as a required property first, by adding a required list with names: 因此,对于确认该标志additional丢失,你需要标记该键为必需的属性首先,通过增加required列出其名称:

schema_data = {
    "type" : "object",
    "properties" : {
        "price" : {"type" : "number"},
        "name" : {"type" : "string"},
        "additional" : {"type" : "number"},
        },
    "required": ["price", "name", "additional"]
}

Now validation will fail your JSON data because additional is missing: 现在,因为验证将失败的JSON数据additional丢失:

>>> validate(json_data, schema_data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../site-packages/jsonschema/validators.py", line 541, in validate
    cls(schema, *args, **kwargs).validate(instance)
  File "/.../site-packages/jsonschema/validators.py", line 130, in validate
    raise error
jsonschema.exceptions.ValidationError: 'additional' is a required property

Failed validating 'required' in schema:
    {'properties': {'additional': {'type': 'number'},
                    'name': {'type': 'string'},
                    'price': {'type': 'number'}},
     'required': ['price', 'name', 'additional'],
     'type': 'object'}

On instance:
    {'name': 'Eggs', 'new': 90, 'price': 34.99}

To make adding more keys invalid, you need to set additionalProperties to false ; 为了增加更多的按键无效,你需要设置additionalPropertiesfalse ; the default is to allow for extra properties: 默认是允许额外的属性:

schema_data = {
    "type" : "object",
    "properties" : {
        "price" : {"type" : "number"},
        "name" : {"type" : "string"},
        "additional" : {"type" : "number"},
        },
    "required": ["price", "name", "additional"],
    "additionalProperties": False
}

However, with additional still missing, the addition of new key isn't found when you use validate() , because the first error found is raised as an exception. 然而, additional人仍下落不明,的加入new关键是没有找到当您使用validate()因为发现的第一个错误会抛出一个例外。

To get all schema validation errors, create a validator object for the schema then use the IValidator.iter_errors() method to list all errors found: 要获取所有模式验证错误,请为模式创建一个验证器对象,然后使用IValidator.iter_errors()方法列出所有发现的错误:

from json_schema.validators import validator_for

validator = validator_for(schema_data)(schema_data)  # get class, create instance
for error in validator.iter_errors(json_data):
    print(error)

and now you get information about each error: 现在您可以获得有关每个错误的信息:

'additional' is a required property

Failed validating 'required' in schema:
    {'additionalProperties': False,
     'properties': {'additional': {'type': 'number'},
                    'name': {'type': 'string'},
                    'price': {'type': 'number'}},
     'required': ['price', 'name', 'additional'],
     'type': 'object'}

On instance:
    {'name': 'Eggs', 'new': 90, 'price': 34.99}
Additional properties are not allowed ('new' was unexpected)

Failed validating 'additionalProperties' in schema:
    {'additionalProperties': False,
     'properties': {'additional': {'type': 'number'},
                    'name': {'type': 'string'},
                    'price': {'type': 'number'}},
     'required': ['price', 'name', 'additional'],
     'type': 'object'}

On instance:
    {'name': 'Eggs', 'new': 90, 'price': 34.99}

Each error object in the loop is a ValidatorError exception object , which has a series of attributes can help you figure out exactly what the problem is, in code. 循环中的每个error对象都是ValidatorError异常对象 ,该对象具有一系列属性,可以帮助您准确地用代码找出问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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