我的程序获取一个包含服务信息的JSON文件 在运行服务程序之前,我想检查JSON文件是否为valide(仅检查是否存在所有必需的密钥) 以下是该程序的标准(必要数据)JSON格式:
{
"service" : "Some Service Name"
"customer" : {
"lastName" : "Kim",
"firstName" : "Bingbong",
"age" : "99",
}
}
现在我正在检查JSON文件验证:
import json
def is_valid(json_file):
json_data = json.load(open('data.json'))
if json_data.get('service') == None:
return False
if json_data.get('customer').get('lastName') == None:
return False
if json_data.get('customer').get('firstName') == None:
return False
if json_data.get('customer').get('age') == None:
return False
return True
实际上,JSON标准格式有20多个密钥。还有其他方法可以检查JSON格式吗?
答案 0 :(得分:7)
您可以考虑jsonschema
来验证您的JSON。这是一个验证您的示例的程序。要将其扩展到“20个密钥”,请将密钥名称添加到"required"
列表中。
import jsonschema
import json
schema = {
"type": "object",
"customer": {
"type": "object",
"required": ["lastName", "firstName", "age"]},
"required": ["service", "customer"]
}
json_document = '''{
"service" : "Some Service Name",
"customer" : {
"lastName" : "Kim",
"firstName" : "Bingbong",
"age" : "99"
}
}'''
try:
# Read in the JSON document
datum = json.loads(json_document)
# And validate the result
jsonschema.validate(datum, schema)
except jsonschema.exceptions.ValidationError as e:
print("well-formed but invalid JSON:", e)
except json.decoder.JSONDecodeError as e:
print("poorly-formed text, not JSON:", e)
资源:
答案 1 :(得分:1)
我想使用jsonschema
(https://pypi.python.org/pypi/jsonschema)可以为你执行。
答案 2 :(得分:0)
首先,请勿使用if x == None
检查无,请使用if x is None
您可以尝试使用set(json_data.keys()) == set(key1, key2, ...)
对于json结构中的任何嵌套字典,都需要重复这一过程。使用集合代替列表具有集合无序的好处,因此与json中的数据顺序无关。
答案 3 :(得分:0)
如果您发现json模式语法令人困惑。根据需要创建json,然后通过online-json-to-schema-converter运行它,然后在上述Rob的示例中使用它。