我需要创建一个函数来验证传入的 json 数据并返回 python 字典。它应该检查 json 文件中是否存在所有必需的字段,并验证这些字段的数据类型。我需要使用 try-catch。您能否提供一些片段或示例来给我答案?
请您参考如下方法:
如果你还没有勾选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)
