Check whether a string is valid JSON or not in Python

JSON is a text format used 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 use the JSON module to validate if the string represents a valid JSON format or not.

Using json.loads() Method

The json module has a method called loads() that loads a valid JSON string to create a JSON object. We can use a try-except block to catch any parsing errors ?

import json

def is_valid_json(json_string):
    try:
        json.loads(json_string)
        return True
    except ValueError:
        return False

# Test with valid JSON
valid_json = '{"Mon": "2pm", "Wed": "9pm", "Fri": "6pm"}'
print(f"String: {valid_json}")
print(f"Valid JSON: {is_valid_json(valid_json)}")
String: {"Mon": "2pm", "Wed": "9pm", "Fri": "6pm"}
Valid JSON: True

Testing Invalid JSON

Let's test with an invalid JSON string that has unquoted values ?

import json

# Invalid JSON - missing quotes around value
invalid_json = '{"Mon": 2pm, "Wed": "9pm", "Fri": "6pm"}'
print(f"String: {invalid_json}")

try:
    json.loads(invalid_json)
    print("Valid JSON")
except ValueError as e:
    print("Invalid JSON")
    print(f"Error: {e}")
String: {"Mon": 2pm, "Wed": "9pm", "Fri": "6pm"}
Invalid JSON
Error: Expecting value: line 1 column 9 (char 8)

Validating Nested JSON

JSON can have nested objects. The validation works the same way for complex structures ?

import json

# Nested JSON structure
nested_json = '{"Timetable": {"Mon": "2pm", "Wed": "9pm"}}'
print(f"String: {nested_json}")

try:
    json_obj = json.loads(nested_json)
    print("Valid JSON")
    print(f"Parsed object: {json_obj}")
except ValueError as e:
    print("Invalid JSON")
String: {"Timetable": {"Mon": "2pm", "Wed": "9pm"}}
Valid JSON
Parsed object: {'Timetable': {'Mon': '2pm', 'Wed': '9pm'}}

Complete Validation Function

Here's a reusable function that validates JSON and provides detailed feedback ?

import json

def validate_json(json_string):
    """Validate if a string is valid JSON"""
    try:
        json.loads(json_string)
        return True, "Valid JSON"
    except json.JSONDecodeError as e:
        return False, f"Invalid JSON: {e}"

# Test multiple cases
test_strings = [
    '{"name": "John", "age": 30}',  # Valid
    '{"name": "John", "age": 30,}',  # Invalid - trailing comma
    '{"name": John, "age": 30}',     # Invalid - unquoted value
    '[1, 2, 3, 4]',                 # Valid array
    'null',                         # Valid null
    'true'                          # Valid boolean
]

for test_str in test_strings:
    is_valid, message = validate_json(test_str)
    print(f"'{test_str}' ? {message}")
'{"name": "John", "age": 30}' ? Valid JSON
'{"name": "John", "age": 30,}' ? Invalid JSON: Expecting property name enclosed in double quotes: line 1 column 25 (char 24)
'{"name": John, "age": 30}' ? Invalid JSON: Expecting value: line 1 column 10 (char 9)
'[1, 2, 3, 4]' ? Valid JSON
'null' ? Valid JSON
'true' ? Valid JSON

Conclusion

Use json.loads() with a try-except block to validate JSON strings. The function raises JSONDecodeError for invalid JSON, making validation straightforward and reliable.

Updated on: 2026-03-15T17:54:14+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements