How do I check if a string is a valid JSON in Python?
Davide S
davide s profile pic

In Python, you can check if a string is a valid JSON using thejson module. Thejson module provides functions for encoding and decoding JSON data, including a method to check the validity of a JSON string. Here's a detailed explanation of how to accomplish this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

import json

def is_valid_json(data):
    try:
   json.loads(data)  # Attempt to load the string as JSON
   return True
    except ValueError:
   return False

json_string = '{"name": "John", "age": 30, "city": "New York"}'

if is_valid_json(json_string):
    print("The string is a valid JSON.")
else:
    print("The string is not a valid JSON.")

In this example, theis_valid_json() function checks the validity of a JSON string by attempting to load it usingjson.loads(). If the loading is successful without raising aValueError exception, it indicates that the string is valid JSON, and the function returnsTrue. Otherwise, it returnsFalse. Thejson.loads() function deserializes a JSON string into a Python object. If the input string is not valid JSON, it will raise aValueError exception. By catching this exception, you can determine if the string is valid JSON or not. Note: This approach checks the syntactical validity of the JSON string. It doesn't guarantee the semantic correctness or conformity to a specific JSON schema. If you need to validate the JSON against a schema, you may consider using additional libraries or tools specifically designed for JSON schema validation. Summary: To check if a string is a valid JSON in Python, you can use thejson module. By attempting to load the string usingjson.loads() and catching aValueError exception, you can determine if the string is valid JSON. This allows you to handle JSON data appropriately in your code and ensure its validity before further processing.