Given a Python String, the task is to check whether the String is a valid JSON object or not. Let’s try to understand the problem using different examples.
Example 1 : Invalid JSON String due to incorrect quotes in Strings
Python3
import json
ini_string = "{'akshat' : 1, 'nikhil' : 2}"
print ( "initial string" , ini_string)
try :
json_object = json.loads(ini_string)
print ( "Is valid json? true" )
except ValueError as e:
print ( "Is valid json? false" )
|
Output:
initial string {'akshat' : 1, 'nikhil' : 2}
Is valid json? false
Explanation: In the above example, the string is an invalid JSON because, the string characters the enclosed in single quotes (‘), but as per valid JSON schema, strings must be enclosed in double quotes (“).
Example 2: Example of Valid JSON Strings
Python3
import json
def is_valid(json_string):
print ( "JSON String:" , json_string)
try :
json.loads(json_string)
print ( " Is valid?: True" )
except ValueError:
print ( " Is valid?: False" )
return None
is_valid( '{"name":"John", "age":31, "Salary":2500000}' )
is_valid( '{ "Subjects": {"Maths":85.01, "Physics":90}}' )
is_valid( '{"success": true}' )
|
Output:
JSON String: {"name":"John", "age":31, "Salary":2500000}
Is valid?: True
JSON String: { "Subjects": {"Maths":85.01, "Physics":90}}
Is valid?: True
JSON String: {"success": true}
Is valid?: True
Example 3: Checking Validity for Multi-Line JSON String
Here we have taken a sample, multi-line Python string, and we’ll try to check the validity of the String for a valid JSON string or not. Although this String contains multiple line-breaks, still json.JSONDecoder able to parse this String.
Python3
import json
def is_valid(json_string):
print ( "JSON String:" , json_string)
try :
json.loads(json_string)
print ( " Is valid?: True" )
except ValueError:
print ( " Is valid?: False" )
return None
json_str =
is_valid(json_str)
|
Output:
JSON String:
{
"Person": [
{"name": "P_1", "age": 42},
{"name": "P_2", "age": 21},
{"name": "P_3", "age": 36}
],
"location": "1.1.0",
"Country": "IND"
}
Is valid?: True