You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.

In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.

Answer from John Flatness on Stack Overflow
Top answer
1 of 8
344

You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.

In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.

2 of 8
238

Example Python script returns a boolean if a string is valid json:

import json

def is_json(myjson):
  try:
    json.loads(myjson)
  except ValueError as e:
    return False
  return True

Which prints:

print is_json("{}")                          #prints True
print is_json("{asdf}")                      #prints False
print is_json('{ "age":100}')                #prints True
print is_json("{'age':100 }")                #prints False
print is_json("{\"age\":100 }")              #prints True
print is_json('{"age":100 }')                #prints True
print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True

Convert a JSON string to a Python dictionary:

import json
mydict = json.loads('{"foo":"bar"}')
print(mydict['foo'])    #prints bar

mylist = json.loads("[5,6,7]")
print(mylist)
[5, 6, 7]

Convert a python object to JSON string:

foo = {}
foo['gummy'] = 'bear'
print(json.dumps(foo))           #prints {"gummy": "bear"}

If you want access to low-level parsing, don't roll your own, use an existing library: http://www.json.org/

Great tutorial on python JSON module: https://pymotw.com/2/json/

Is String JSON and show syntax errors and error messages:

sudo cpan JSON::XS
echo '{"foo":[5,6.8],"foo":"bar" bar}' > myjson.json
json_xs -t none < myjson.json

Prints:

, or } expected while parsing object/hash, at character offset 28 (before "bar}
at /usr/local/bin/json_xs line 183, <STDIN> line 1.

json_xs is capable of syntax checking, parsing, prittifying, encoding, decoding and more:

https://metacpan.org/pod/json_xs

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-check-whether-a-string-is-valid-json-or-not
Python | Check whether a string is valid json or not - GeeksforGeeks
July 11, 2025 - 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 ("). ... # 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?
Discussions

Verify if a String is JSON in python? - Stack Overflow
To verify the string would require parsing it - so if you checked then converted it would literally take twice as long. Catching the exception is the best way. Interestingly, you can still use an if-else style expression: try: json_object = json.loads(json_string) except ValueError as e: pass # invalid json else: pass # valid json ... Keep in mind that testing and catching an exception can be blazingly fast in Python... More on stackoverflow.com
🌐 stackoverflow.com
July 2, 2012
Python: check if string is JSON without raising an exception? - Stack Overflow
I have a stream of strings where I need to analyze each one and check whether it is a valid JSON. The pythonic way (EAFP) dictates something like this: import json def parse_json(string): try:... More on stackoverflow.com
🌐 stackoverflow.com
August 25, 2020
How to check if a string is a valid JSON in python - Stack Overflow
I have a python script providing command line / output in console on remote linux. I have another script which is reading this output on local machine. Output is in below format: ABC: NEG BCD: NE... More on stackoverflow.com
🌐 stackoverflow.com
April 15, 2014
How to check if string is valid json in template
hi im trying to find a way in template code to check if a string is valid json checked chagpt but it gave me false answers and non supported syntax if I do this code {% set json_string = 'invalid' %} {% set json_data… More on community.home-assistant.io
🌐 community.home-assistant.io
0
0
June 3, 2025
🌐
Reddit
reddit.com › r/learnpython › how to check if something is in a json object before running if statement
r/learnpython on Reddit: How to check if something is in a JSON object before running if statement
September 15, 2023 -

Ok... This is a little complicated... So... Sorry in advance

I have a function that returns attributes of a video file (FFprobe) in a JSON object, and then a little factory that parses the JSON looking for specific attributes, and running if statements on those attributes.

I.E. One of attributes in the JSON is subtitle format. So if the subtitle format != a desired format, then set a variable that is used in another format for encoding the subtitle to the desired format

The issue that I have run into so that sometimes those attributes (like subtitle) don't exist in the JSON because they do not exist in the file.

So I sort of need to check if the attribute in the JSON exists, before I check to see if if that attribute is the desired attribute and start setting variables

How do I do this?

Would it be as simple as:

json_object= json.loads(studentJson)
if "subtitle_format" in json_object: 
    print("Key exist in json_object") 
    print(subtitle_format["ASS"], " is the subtitle format") 
else: 
    print("Key doesn't exist in JSON data")

If yes, would I get yelled at if the if statement had a few layers? Psudo:

if subtitle_format in json_object:
    if subtitle_format == ass
         if subtitle_format == english
             encode 

🌐
PYnative
pynative.com › home › python › json › validate json data using python
Validate JSON data using Python
May 14, 2021 - Check if a string is valid JSON in Python. Validate JSON Schema using Python. Validates incoming JSON data by checking if there all necessary fields present in JSON and also verify data types of those fields
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to check whether a string is valid json in python
5 Best Ways to Check Whether a String is Valid JSON in Python - Be on the Right Side of Change
March 11, 2024 - 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. ... 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))
🌐
TutorialsPoint
tutorialspoint.com › check-whether-a-string-is-valid-json-or-not-in-python
Check whether a string is valid JSON or not in Python
If there is error we consider the JSON string as invalid. ... import json Astring= '{"Mon" : "2pm", "Wed" : "9pm" ,"Fri" : "6pm"}' # Given string print("Given string", Astring) # Validate JSON try: json_obj = json.loads(Astring) print("A valid JSON") except ValueError as e: print("Not a valid JSON") # Checking again Astring= '{"Mon" : 2pm, "Wed" : "9pm" ,"Fri" : "6pm"}' # Given string print("Given string", Astring) # Validate JSON try: json_obj = json.loads(Astring) print("A valid JSON") except ValueError as e: print("Not a valid JSON") # Nested levels Astring = '{ "Timetable": {"Mon" : "2pm", "Wed" : "9pm"}}' # Given string print("Given string", Astring) # Validate JSON try: json_obj = json.loads(Astring) print("A valid JSON") except ValueError as e: print("Not a valid JSON")
🌐
Quora
quora.com › How-does-one-check-if-an-object-is-python-is-JSON-serializable
How does one check if an object is python is JSON serializable? - Quora
Answer: The easiest way is to try to dump the object to JSON. If you want something a bit more clean-cut, you can write a function like this: [code]def safe_json(data): if data is None: return True elif isinstance(data, (bool, int, float)): ...
Find elsewhere
Top answer
1 of 2
1

More compact way should be like this. Json lib process only str, bytes or bytearray structures, so only consider them. Instead of if len(text)==0, if not text is much faster for long strings, we don't want to know length of text. Json lib may raise JsonDecoderError. First last characters of text can be checked back-reference with regex but I tried possible edge cases such as '{]' and '[}', they don't fail.

def is_json(text: str) -> bool:
    from json import loads, JSONDecodeError
 
    if not isinstance(text, (str, bytes, bytearray)):
        return False
    if not text:
        return False
    text = text.strip()
    if text[0] in {'{', '['} and text[-1] in {'}', ']'}:
        try:
            loads(text)
        except (ValueError, TypeError, JSONDecodeError):
            return False
        else:
            return True
    else:
        return False

EDIT: We should check whether text is empty or not, not to raise IndexError.

def is_json(text: str) -> bool:
    if not isinstance(text, (str, bytes, bytearray)):
        return False
    if not text:
        return False
    text = text.strip()
    if text:
        if text[0] in {'{', '['} and text[-1] in {'}', ']'}:
            try:
                loads(text)
            except (ValueError, TypeError, JSONDecodeError):
                return False
            else:
                return True
        else:
            return False
    return False
2 of 2
0

for speed issue you can use multiprocessing to speed up the parsing , for example by utilizing 5 workers in multiprocessing you parse 5 string at a time instead of one

if i understand second part of question , for custom exception do something like this to get custom error for different error that return by json:

def parse_json(string):
    try:
        return json.loads(string)
    except exception1 as ex1:
        print(ex1)
        return string
    except exception2 as ex2:
        print(ex2)
        return string
    exc....

or if you don't want to get any exception on error raising do this , just give it a pass to do nothing , not showing up anything:

def parse_json(string):

try:
    return json.loads(string)
except exception1 as ex1:
    pass
🌐
InterSystems
community.intersystems.com › post › validate-json-string
Validate JSON string | InterSystems Developer Community
July 18, 2023 - set a="{name:""John Doe"" " set b="{""name"":""John Doe"" }" write ##class(some.class).IsJSON(a) --> 0 write ##class(some.class).IsJSON(b) --> 1 write ##class(some.class).IsJSON() --> <UNDEFINED>zIsJSON+1^... *str ... I have used the same solution already. Tnx. Regards, Matjaž. ... https://community.intersystems.com/post/function-check-if-string-json-o… another article to validate JSON string ... Class dc.Demo { ClassMethod ValidateJSON(data As %String = "") As %Status [ Language = python ] { import iris import json from json import JSONDecodeError try: json.loads(data) return iris.system.Status.OK() except JSONDecodeError as ex: return iris.system.Status.Error(5001, f"{ex.msg}: line {ex.lineno} column {ex.colno} (char {ex.pos})") except Exception as ex: return iris.system.Status.Error(5001, repr(ex)) } }
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.3 documentation
3 weeks ago - If None (the default), it is equivalent to int(num_str). This can be used to parse JSON integers into custom datatypes, for example float. parse_constant (callable | None) – If set, a function that is called with one of the following strings: '-Infinity', 'Infinity', or 'NaN'.
🌐
Home Assistant
community.home-assistant.io › configuration
How to check if string is valid json in template - Configuration - Home Assistant Community
June 3, 2025 - hi im trying to find a way in template code to check if a string is valid json checked chagpt but it gave me false answers and non supported syntax if I do this code {% set json_string = 'invalid' %} {% set json_data…
🌐
Reddit
reddit.com › r/learnpython › checking for json type
r/learnpython on Reddit: Checking for JSON type
November 14, 2020 - Subreddit for posting questions and asking for general advice about all topics related to learning python. ... I am looking to enforce a precondition for a function stating that the input must be a json string**.** for a method to check if variable S is a regular string, I can simply check the type by asking return type(s) == str; I am wondering if there is a similar method that is used to check for json strings.
🌐
Flexiple
flexiple.com › python › python-json-validator
Python JSON Validator - Flexiple
March 28, 2024 - As a result, the JSON validation function detected this discrepancy and reported a "JSON validation error." This example demonstrates how the Python JSON Validator can effectively check the structure and data types of JSON objects against a ...
🌐
Edureka Community
edureka.co › home › community › categories › web development › php › how to check if a string is json or not
How to check if a string is JSON or not | Edureka Community
August 19, 2020 - have a simple AJAX call, and the server will return either a JSON string with useful data or an error ... }else{ //report the error alert(data); }
🌐
Python.org
discuss.python.org › python help
How to Check if key Error key exist in a JSON String Python - Python Help - Discussions on Python.org
September 24, 2022 - If i want to check if my JSON String contain Error from API request, i have a string that saved the respond, Example final = response.json() And i want to check if the API response error
🌐
CopyProgramming
copyprogramming.com › howto › python-python-check-if-not-in-request-json
Python: Check if a value is not present in JSON of a request using Python
March 24, 2023 - Attempting json.loads() may result in a ValueError error if the input string is not JSON decodable. The philosophy for this type of scenario in Python is commonly referred to as EAFP, which stands for "easier to ask for forgiveness than permission. ... import json def is_json(myjson): try: json.loads(myjson) except ValueError as e: return False return True
🌐
GitHub
github.com › nlohmann › json › issues › 653
how should I check a string is valid JSON string ? · Issue #653 · nlohmann/json
July 11, 2017 - I read all examples, but I didnt find a way to check a string is valid JSON string. Is there an API to achieve this ? or I have to use "try catch" to check exceptions ? thanks ^_^
Author   zhishupp