Python | Check whether a string is valid json or not

Given a string, the task is to check whether a string is valid json object or not. Let’s try to understand the problem using different examples.

Code #1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# checking whether string
# is valid json or not
  
import json
  
ini_string = "{'akshat' : 1, 'nikhil' : 2}"
  
# printing initial ini_string
print ("initial string", ini_string)
  
# checking for string
try:
    json_object = json.loads(ini_string)
    print ("Is valid json? true")
except ValueError as e:
    print ("Is valid json? false")

chevron_right


Output:

initial string {'akshat' : 1, 'nikhil' : 2}
Is valid json? false

 
Code #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# checking whether string
# is valid json or not
  
import json
  
#ini_string = '{"Geek" : 1,"forGeeks" : 2}'
  
a = '{"name":"John", "age":31, "Salary":25000}'
b = '{ "Subjects": {"Maths":85, "Physics":90}}'
  
#printing initial ini_string
print ("initial strings given - \n", a, "\n", b)
  
#checking for string
try:
    json_object1 = json.loads(a)
    json_object2 = json.loads(b)
    print ("Is valid json? true")
      
except ValueError as e:
    print ("Is valid json? false")

chevron_right


Output:

initial strings given - 
 {"name":"John", "age":31, "Salary":25000} 
 { "Subjects": {"Maths":85, "Physics":90}}
Is valid json? true


My Personal Notes arrow_drop_up

Programming freak_tech Enthusiast and have interest in learning new upcoming technologies.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.