How to check JSON format validation?
Question:
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?
Answers:
I guess using of jsonschema
(https://pypi.python.org/pypi/jsonschema) can perform thot for you.
First, don’t check for None using if x == None
, use if x is None
You might try to simplify it slightly by checking the keys using set(json_data.keys()) == set(key1, key2, ...)
That would need to be repeated for any nested dictionaries in your json structure. Using sets instead of lists has the benefit of sets being unordered so it doesn’t matter the order of the data in your json.
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:
If your finding the json schema syntax confusing. Create your json as you want it and then run it though online-json-to-schema-converter and then use it in Rob’s example above.
In case someone does not want to use jsonschema to validate then below code can be used to validate only the keys
of json
as requested in this question.
import json
def validateJsonKeys(myjson):
if set(myjson.keys()) == {'service', 'customer'}:
if set(myjson['customer'].keys()) == {'lastName', 'firstName', 'age'}:
return True
return False
else:
return False
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?
I guess using of jsonschema
(https://pypi.python.org/pypi/jsonschema) can perform thot for you.
First, don’t check for None using if x == None
, use if x is None
You might try to simplify it slightly by checking the keys using set(json_data.keys()) == set(key1, key2, ...)
That would need to be repeated for any nested dictionaries in your json structure. Using sets instead of lists has the benefit of sets being unordered so it doesn’t matter the order of the data in your json.
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:
If your finding the json schema syntax confusing. Create your json as you want it and then run it though online-json-to-schema-converter and then use it in Rob’s example above.
In case someone does not want to use jsonschema to validate then below code can be used to validate only the keys
of json
as requested in this question.
import json
def validateJsonKeys(myjson):
if set(myjson.keys()) == {'service', 'customer'}:
if set(myjson['customer'].keys()) == {'lastName', 'firstName', 'age'}:
return True
return False
else:
return False