How to Check if String is Valid JSON in Python
To check if a string is valid JSON in Python, use the
json.loads() function inside a try-except block. If json.loads() parses the string without errors, it is valid JSON; otherwise, it is not.Syntax
Use the json.loads() function to parse a JSON string. Wrap it in a try-except block to catch json.JSONDecodeError if the string is not valid JSON.
json.loads(json_string): Parses the JSON string.try-except: Handles parsing errors gracefully.
python
import json try: json.loads(json_string) # If no error, json_string is valid JSON except json.JSONDecodeError: # json_string is not valid JSON
Example
This example shows how to check if a string is valid JSON. It prints Valid JSON if parsing succeeds, otherwise Invalid JSON.
python
import json def is_valid_json(json_string): try: json.loads(json_string) return True except json.JSONDecodeError: return False # Test with valid JSON string valid_str = '{"name": "Alice", "age": 30}' print("Valid JSON" if is_valid_json(valid_str) else "Invalid JSON") # Test with invalid JSON string invalid_str = '{name: Alice, age: 30}' print("Valid JSON" if is_valid_json(invalid_str) else "Invalid JSON")
Output
Valid JSON
Invalid JSON
Common Pitfalls
Common mistakes when checking JSON validity include:
- Not catching
json.JSONDecodeError, which causes the program to crash. - Assuming a string is JSON just because it looks like one (e.g., missing quotes around keys).
- Confusing JSON format with Python dictionaries (JSON keys must be in double quotes).
python
import json # Wrong way: no error handling json_string = '{name: Alice}' # This will raise an exception and stop the program # json.loads(json_string) # Right way: use try-except try: json.loads(json_string) print("Valid JSON") except json.JSONDecodeError: print("Invalid JSON")
Output
Invalid JSON
Quick Reference
Summary tips for checking JSON validity in Python:
- Use
json.loads()to parse the string. - Wrap parsing in
try-except json.JSONDecodeErrorto catch invalid JSON. - Remember JSON keys must be double-quoted strings.
- Test with both valid and invalid JSON strings to confirm your check works.
Key Takeaways
Use json.loads() inside try-except to check JSON validity safely.
Catch json.JSONDecodeError to handle invalid JSON strings without crashing.
JSON keys must be double-quoted strings, unlike Python dict keys.
Testing with both valid and invalid JSON strings helps verify your check.
Avoid assuming a string is JSON without parsing it first.