Check whether a string is valid JSON or not in Python

PythonServer Side ProgrammingProgramming

JSON is a type of text format use to exchange data easily between various computer programs. It has a specific format which Python can validate. In this article we will consider a string and using JSON module we will validate if the string represents a valid JSON format or not.

Creating JSON Object

The json module has method called loads. It loads a valid json string to create a Json object. In this example we load the string and check that there is no error in loading the JSON object. If there is error we consider the JSON string as invalid.

Example

 Live Demo

import json
Astring= '{"Mon" : "2pm", "Wed" : "9pm" ,"Fri" : "6pm"}'
# Given string
print("Given string", Astring)
# Validate JSON
try:
   json_obj = json.loads(Astring)
   print("A valid JSON")
except ValueError as e:
   print("Not a valid JSON")
# Checking again
Astring= '{"Mon" : 2pm, "Wed" : "9pm" ,"Fri" : "6pm"}'
# Given string
print("Given string", Astring)
# Validate JSON
try:
   json_obj = json.loads(Astring)
   print("A valid JSON")
except ValueError as e:
   print("Not a valid JSON")
# Nested levels
Astring = '{ "Timetable": {"Mon" : "2pm", "Wed" : "9pm"}}'
# Given string
print("Given string", Astring)
# Validate JSON
try:
   json_obj = json.loads(Astring)
   print("A valid JSON")
except ValueError as e:
   print("Not a valid JSON")

Output

Running the above code gives us the following result −

Given string {"Mon" : "2pm", "Wed" : "9pm" ,"Fri" : "6pm"}
A valid JSON
Given string {"Mon" : 2pm, "Wed" : "9pm" ,"Fri" : "6pm"}
Not a valid JSON
Given string { "Timetable": {"Mon" : "2pm", "Wed" : "9pm"}}
A valid JSON
raja
Published on 20-May-2020 13:32:37
Advertisements