
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a String is Valid JSON in Python
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
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
Advertisements