使用python验证JSON数据

Len*_*Dan 1 python validation json python-3.x

我是python的新手,所以您愿意帮助我吗?这似乎是一个微不足道的问题。我需要创建一个函数来验证传入的json数据并返回python dict。它应该检查json文件中是否存在所有必要的字段,并验证该字段的数据类型。我需要使用try-catch。您能提供一些片段或示例给我答案吗?

ATe*_*ive 7

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

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

  • @ATernative,问题是检查是否存在必要的字段,而不是某些字符串能够解析为 JSON。 (7认同)
  • 这是 [Linting](https://en.wikipedia.org/wiki/Lint_(software))。Linting 与[模式验证](https://fullstack.wiki/json-schema/index) 不同。 (4认同)
  • “JSONDecodeError”未定义并且本身会产生错误!正确的名称是 'json.decoder.JSONDecodeError' ! (2认同)

小智 6

如果您尚未检查jsonschema库,则对验证数据很有用。JSON模式是一种描述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)
Run Code Online (Sandbox Code Playgroud)