Python | Check whether a string is valid json or not
Last Updated :
14 Dec, 2023
Given a Python String, the task is to check whether the String is a valid JSON object or not. Let's try to understand the problem using different examples in Python.
Validate JSON String in Python
There are various methods to Validate JSON schema in Python here we explain some generally used methods for validating JSON schema in Python which are the following:
- Check Whether a String Is Valid JSON
- Use JSON Schema to Validate JSON Strings
- Checking Validity for Multi-Line JSON String
Check Whether a String Is Valid JSON
In the below example, the string is an invalid JSON because, the string characters are enclosed in single quotes ('), but as per valid JSON schema, strings must be enclosed in double quotes (").
Python3
# Python code to demonstrate
# checking whether string
# is valid json or not
import json
ini_string = "{'akshat' : 1, 'nikhil' : 2}"
# printing initial ini_string
print ("initial string", ini_string)
# checking for string
try:
json_object = json.loads(ini_string)
print ("Is valid json? true")
except ValueError as e:
print ("Is valid json? false")
Output:
initial string {'akshat' : 1, 'nikhil' : 2}
Is valid json? false
Use JSON Schema to Validate JSON Strings
In this example the below code uses a function, `is_valid`, to check JSON string validity with `json.loads()`. It tests the function on three JSON strings containing various data types and prints whether each string is valid or not.
Python3
import json
# function to check for JSON String validity
def is_valid(json_string):
print("JSON String:", json_string)
try:
json.loads(json_string)
print(" Is valid?: True")
except ValueError:
print(" Is valid?: False")
return None
# checking for string and integers
is_valid('{"name":"John", "age":31, "Salary":2500000}')
# checking for integer and float
is_valid('{ "Subjects": {"Maths":85.01, "Physics":90}}')
# checking for boolean type values
is_valid('{"success": true}')
Output:
JSON String: {"name":"John", "age":31, "Salary":2500000}
Is valid?: True
JSON String: { "Subjects": {"Maths":85.01, "Physics":90}}
Is valid?: True
JSON String: {"success": true}
Is valid?: True
Checking Validity for Multi-Line JSON String
Here we have taken a sample, multi-line Python string, and we'll try to check the validity of the String for a valid JSON string or not. Although this String contains multiple line-breaks, still json.JSONDecoder able to parse this String.
Python3
import json
# function to check for JSON String validity
def is_valid(json_string):
print("JSON String:", json_string)
try:
json.loads(json_string)
print(" Is valid?: True")
except ValueError:
print(" Is valid?: False")
return None
# parsing multi-line JSON string
json_str = """
{
"Person": [
{"name": "P_1", "age": 42},
{"name": "P_2", "age": 21},
{"name": "P_3", "age": 36}
],
"location": "1.1.0",
"Country": "IND"
}
"""
# call function for validation check
# of the Python String
is_valid(json_str)
Output:
JSON String:
{
"Person": [
{"name": "P_1", "age": 42},
{"name": "P_2", "age": 21},
{"name": "P_3", "age": 36}
],
"location": "1.1.0",
"Country": "IND"
}
Is valid?: True
Similar Reads
Check Whether String Contains Only Numbers or Not - Python We are given a string s="12345" we need to check whether the string contains only number or not if the string contains only number we will return True or if the string does contains some other value then we will return False. This article will explore various techniques to check if a string contains
3 min read
Check if String is Empty or Not - Python We are given a string and our task is to check whether it is empty or not. For example, if the input is "", it should return True (indicating it's empty), and if the input is "hello", it should return False. Let's explore different methods of doing it with example:Using Comparison Operator(==)The si
2 min read
Python | Check if string is a valid identifier Given a string, write a Python program to check if it is a valid identifier or not. An identifier must begin with either an alphabet or underscore, it can not begin with a digit or any other special character, moreover, digits can come after gfg : valid identifier 123 : invalid identifier _abc12 : v
3 min read
Check if email address valid or not in Python Given a string, write a Python program to check if the string is a valid email address or not. An email is a string (a subset of ASCII characters) separated into two parts by the @ symbol, a "personal_info" and a domain, that is [email protected]: Email Address Validator using re.match()P
3 min read
Python program to check if a given string is Keyword or not This article will explore how to check if a given string is a reserved keyword in Python. Using the keyword We can easily determine whether a string conflicts with Python's built-in syntax rules.Using iskeyword()The keyword module in Python provides a function iskeyword() to check if a string is a k
2 min read