使用 python 验证 JSON 数据

问题描述 投票:0回答:4

我需要创建一个函数来验证传入的 json 数据并返回 python 字典。它应该检查 json 文件中是否存在所有必需的字段,并验证这些字段的数据类型。我需要使用try-catch。您能否提供一些片段或示例来给我答案?

python json python-3.x validation
4个回答
52
投票

如果您还没有检查 jsonschema 库,它对于验证数据可能很有用。 JSON Schema是描述JSON内容的一种方式。该库仅使用该格式根据给定的模式进行验证。

我从基本用法做了一个简单的例子。

import json
from jsonschema import validate

# Describe what kind of json you expect.
schema = {
    "type" : "object",
    "properties" : {
        "description" : {"type" : "string"},
        "status" : {"type" : "boolean"},
        "value_a" : {"type" : "number"},
        "value_b" : {"type" : "number"},
    },
}

# Convert json to python object.
my_json = json.loads('{"description": "Hello world!", "status": true, "value_a": 1, "value_b": 3.14}')

# Validate will raise exception if given json is not
# what is described in schema.
validate(instance=my_json, schema=schema)

# print for debug
print(my_json)

10
投票

当您使用 JSON 文件时,您可以使用以下示例:

import json
def validate(filename):
    with open(filename) as file:
        try:
            data = json.load(file) # put JSON-data to a variable
            print("Valid JSON")    # in case json is valid
            return data
        except json.decoder.JSONDecodeError:
            print("Invalid JSON")  # in case json is invalid

3
投票

我遇到了同样的问题,并且对使用 jsonschema 的现有解决方案不满意。它给出了可怕的错误消息,对用户来说根本不友好。

我编写了自己的库来定义模式,它比 jsonschema 有很多附加功能:

https://github.com/FlorianDietz/syntaxTrees

它提供非常精确的错误消息,允许您编写代码来自定义验证过程,让您定义对经过验证的 JSON 进行操作的函数,甚至为您定义的模式创建 HTML 文档。

模式被定义为类,类似于 Django 定义模型的方式:

class MyExampleNode(syntaxTreesBasics.Node):
    field_1 = fields.Float(default=0)
    field_2 = fields.String()
    field_3 = fields.Value('my_example_node', null=True, default=None)
    class Meta:
        name = 'my_example_node'

2
投票

虽然 Jsonschema 模块很好,但文档缺少复杂的示例。并且库不会报告任何无效模式的错误,只是忽略!

这是示例:

from jsonschema import validate

set_tl_schema = {
    "type" : "object",
    "properties" :  {

    "level": {
      "value": {"type" : "number"},
      "updatedAt": {"type" : "number"}
    }
}
}

x = {'level': {'updatedAt': '1970-01-01T00:00:00.000Z', 'value': 1}, }

try:
    validate(instance=x, schema=set_tl_schema)
except jsonschema.exceptions.ValidationError as ex:
    print(ex)

错误是该级别还需要属性字段。但验证者永远不会向你报告这一点。

我发现非常高效且易于使用的模块:

https://pypi.org/project/json-checker/

>>> from json_checker import Checker

>>> current_data = {'first_key': 1, 'second_key': '2'}
>>> expected_schema = {'first_key': int, 'second_key': str}


>>> checker = Checker(expected_schema)
>>> result = checker.validate(current_data)
© www.soinside.com 2019 - 2024. All rights reserved.