Issue
My program gets a JSON file that has an information for service.
Before run the service program, I want to check if the JSON file is valide(Only check whether all necessary keys exist).
Below is the standard(necessary datas) JSON format for this program:
{
"service" : "Some Service Name"
"customer" : {
"lastName" : "Kim",
"firstName" : "Bingbong",
"age" : "99",
}
}
Now I am checking the JSON file validation like this:
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
Actually, the JSON standard format has more than 20 keys. Is there any other way to check the JSON format?
Solution
You might consider jsonschema
to validate your JSON. Here is a program that validates your example. To extend this to your "20 keys", add the key names to the "required"
list.
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)
Resources:
Answered By - Robᵩ Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.