Python 如何检查JSON格式验证?
我的程序得到一个JSON文件,其中包含服务信息。Python 如何检查JSON格式验证?,python,json,Python,Json,我的程序得到一个JSON文件,其中包含服务信息。 在运行服务程序之前,我想检查JSON文件是否有效(只检查是否存在所有必要的密钥)。 以下是此程序的标准(必要数据)JSON格式: { "service" : "Some Service Name" "customer" : { "lastName" : "Kim", "firstName" : "Bingbong", "age" : "99", } } 现在我检查JSON文
在运行服务程序之前,我想检查JSON文件是否有效(只检查是否存在所有必要的密钥)。
以下是此程序的标准(必要数据)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格式?我想使用
jsonschema
()可以为您执行此操作。首先,如果x==None,请不要使用检查无,如果x为None,请使用
通过使用set(json_data.keys())==set(key1,key2,…)
这需要对json结构中的任何嵌套字典重复。使用集合代替列表有助于设置无序,因此与JSON中的数据顺序无关。您可以考虑验证JSON。下面是一个验证您的示例的程序。要将此扩展到“20个键”,请将键名添加到
“必需”
列表中
import jsonschema
import json
schema = {
"type": "object",
"properties": {
"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)
资源:
如果您发现json模式语法令人困惑。根据需要创建json,然后运行它,然后在Rob的上述示例中使用它。这可能会有所帮助:也许(没有经验,只是最近偶然发现了这个)。@BingbongKim当然,祝你好运!但是如何检查模式
的格式是否正确?例如,如果我碰巧忘记为属性编写类型,我如何检查这个输入错误?不确定草稿版本是否重要,但我认为在最新版本中测试时,您的模式是错误的。需要将客户
包装在属性
中。尝试从数据中删除lastName
,然后您就可以看到它了。如果所需字段没有实际传递,这似乎不会失败:您确定这是正确的代码(尝试删除一个,比如说'lastName',Try except
仍然不except)?谢谢,@gented!我感谢你的评论。我已经修正了这个例子。谢谢,@Cyker。我很抱歉没有尽快回复。我已经修正了这个例子。