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

🌐
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 

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
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 key Error key exist in a JSON String Python
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 More on discuss.python.org
🌐 discuss.python.org
0
0
September 24, 2022
Python: check if string is JSON without raising an exception? - Stack Overflow
Ideally, I'd like the json.loads() function to return a pre-defined value when the parsing fails instead of raising an exception. 2017-03-07T17:40:41.253Z+00:00 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Results of the October 2025 Community Asks Sprint: copy button for code... Chat room owners can now establish room guidelines ... 0 Using python, how can I check if a string ... More on stackoverflow.com
🌐 stackoverflow.com
August 25, 2020
🌐
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?
🌐
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")
🌐
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))
🌐
Python
docs.python.org › 3 › library › json.html
json — JSON encoder and decoder
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'.
Find elsewhere
🌐
InterSystems
community.intersystems.com › post › validate-json-string
Validate JSON string | InterSystems Developer Community
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)) } }
🌐
w3resource
w3resource.com › python-exercises › python-json-exercise-8.php
Python JSON: Check whether a JSON string contains complex object or not - w3resource
Write a Python program to check whether a JSON string contains complex object or not. ... import json def is_complex_num(objct): if '__complex__' in objct: return complex(objct['real'], objct['img']) return objct complex_object =json.loads('{"__complex__": true, "real": 4, "img": 5}', object_hook = is_complex_num) simple_object =json.loads('{"real": 4, "img": 3}', object_hook = is_complex_num) print("Complex_object: ",complex_object) print("Without complex object: ",simple_object)
🌐
YouTube
youtube.com › lindevs
How to Check if String is Valid JSON using Python - YouTube
Code snippet can be found in the website:https://lindevs.com/check-if-string-is-valid-json-using-python#Python #JSON #CodeSnippet
Published   January 7, 2022
Views   155
🌐
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
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
🌐
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
Your json subclass could check if there’s a method named (for instance) “encode” or “json_encode” in the class being encoded and call that. That would be a very useful json subclass! ... MASTER OF SCIENCE in Master of Science Degrees & Data Science, Anna University, Tamil Nadu, India (Graduated 2007) · Author has 648 answers and 338.6K answer views · 4y · 1. Checking for __iter__ works on sequence types, but it would fail on e.g. strings in Python...
🌐
YouTube
youtube.com › watch
How do I check if a string is valid JSON in Python?
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
Published   March 5, 2023
🌐
PYnative
pynative.com › home › python › json › python check if key exists in json and iterate the json array
Python Check if key exists in JSON and iterate the JSON array
May 14, 2021 - Let’s see how to use a default value if the value is not present for a key. As you know, the json.loads method converts JSON data into Python dict so we can use the get method of dict class to assign a default value to the key if the value is missing.