5 Best Ways to Check Whether a String is Valid JSON in Python

πŸ’‘ Problem Formulation: In Python, it’s a common scenario to receive a string and need to determine if it’s a valid JSON object. For example, if you have the string '{"name": "Alice", "age": 30}', the desired output is a confirmation that this is indeed valid JSON format. This article explores methods to perform this validation effectively.

Method 1: Using the json.loads() Method

Python’s standard library includes the json module, which has a loads() function to deserialize a JSON document to a Python object. If the string is not a valid JSON, this method will raise a json.JSONDecodeError.

Here’s an example:

import json

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

# Test the function
json_test = '{"name": "Alice", "age": 30}'
print(is_valid_json(json_test))

Output:

True

This code snippet defines a function is_valid_json that uses json.loads() to attempt to parse a string as JSON. If parsing succeeds, it returns True; if it fails due to incorrect formatting, it returns False.

Method 2: Using the isinstance() Check After Loading JSON

After successfully parsing the JSON string with json.loads(), we can check if the result is a dictionary, which implies the input was a valid JSON object (since JSON is essentially key-value pairs).

Here’s an example:

import json

def is_valid_json_dict(json_string):
    try:
        result = json.loads(json_string)
        return isinstance(result, dict)
    except json.JSONDecodeError:
        return False

# Test the function
json_test = '{"name": "Alice", "age": 30}'
print(is_valid_json_dict(json_test))

Output:

True

In this example, the function is_valid_json_dict not only attempts to parse the JSON string but also checks if the result is a dictionary, which ensures that the input string is a JSON object.

Method 3: Validating JSON Schema

If you need to validate not just the format but also the structure according to a predefined schema, you can use the jsonschema library. This requires installing an additional package but provides stronger validation.

Here’s an example:

from jsonschema import validate
from jsonschema.exceptions import ValidationError
import json

def is_valid_json_by_schema(json_string, schema):
    try:
        json_data = json.loads(json_string)
        validate(instance=json_data, schema=schema)
        return True
    except (json.JSONDecodeError, ValidationError):
        return False

# Test the function
json_test = '{"name": "Alice", "age": 30}'
schema = {
    "type" : "object",
    "properties" : {
        "name" : {"type" : "string"},
        "age" : {"type" : "number"}
    },
}
print(is_valid_json_by_schema(json_test, schema))

Output:

True

This function, is_valid_json_by_schema, verifies whether the JSON string matches a specific schema, providing a way to ensure the data has the correct structure and data types expected.

Method 4: Using ast.literal_eval() with JSON Like Objects

Although not recommended for arbitrary or untrusted input, you can use the ast.literal_eval() to safely evaluate a string containing Python literal structures, which can sometimes resemble JSON objects. Caution is advised since this method is not intended for JSON but for Python literals.

Here’s an example:

import ast

def is_valid_json_like(json_string):
    try:
        result = ast.literal_eval(json_string)
        return isinstance(result, dict)
    except (ValueError, SyntaxError):
        return False

# Test the function with a string that looks like a JSON object
json_test = "{'name': 'Alice', 'age': 30}"
print(is_valid_json_like(json_test))

Output:

True

This function, is_valid_json_like, leverages ast.literal_eval() to evaluate a string as a Python dictionary, then checks the result to confirm if it’s JSON-like. However, it is not the recommended method for JSON validation and should be used with care.

Bonus One-Liner Method 5: Using a Simple Lambda with json.loads()

For quick and casual checks, you might prefer a one-liner lambda function. This approach isn’t very different from Method 1 but demonstrates Python’s syntactic sugar for brevity.

Here’s an example:

import json

is_valid_json = lambda json_string: json.loads(json_string) and True or False

# Test the lambda
json_test = '{"name": "Alice", "age": 30}'
print(is_valid_json(json_test))

Output:

True

This one-liner creates an anonymous function that tries to parse a JSON string using json.loads() and implicitly returns True or False based on whether the parse is successful or raises an exception.

Summary/Discussion

  • Method 1: Using json.loads(). It’s straightforward and uses the standard library. However, it may not validate JSON structure against a schema.
  • Method 2: Using isinstance() after loading JSON. A good quick check to confirm an object’s type after loading but doesn’t provide schema validation.
  • Method 3: JSON Schema Validation. It’s the strongest way to validate both format and schema of JSON data but requires an extra package.
  • Method 4: Python-like JSON validation using ast.literal_eval(). This is not a typical method for validating JSON and should be used with caution, as it evaluates Python literals.
  • Method 5: One-liner lambda function. This provides a concise way to perform a quick check but lacks the explicit error handling of Method 1.