Verify if a String is JSON in python?

Question:

I have a string in Python, I want to know if it is valid JSON.

json.loads(mystring) will raise an error if the string is not JSON but I don’t want to catch an exception.

I want something like this, but it doesn’t work:

if type(mysrting) == dict:
    myStrAfterLoading = json.loads(mystring)
else:
    print "invalid json passed"

Do I have to catch that ValueError to see if my string is JSON?

Asked By: eligro

||

Answers:

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
Answered By: DanielB

Is there any reason you don’t want to catch the exception?

Keep in mind that testing and catching an exception can be blazingly fast in Python, and is often the Pythonic way of doing things, instead of testing for type (basically, trust duck typing and react accordingly).

To put your mind a bit more at ease, take a look here:
Python if vs try-except

If you’re still worried about readability, add a comment to the code to explain why you’re using try/except 😉

I struggled with this approach myself in the past coming from a Java background, but this is indeed the simplest way of doing this in Python… and simple is better than complex.

Answered By: pcalcao

The correct answer is: stop NOT wanting to catch the ValueError.

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

import json

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

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
Answered By: JosefAssad

why parsing when you can use types as follows:

def is_json(myjson):
    return type(myjson) == type({})

def is_json_arr(myjson):
    return type(myjson) == type([{}])
Answered By: Hesham Yassin

The safest function, which also catches TypeError which happens when None type is passed

import json

def json_loads_safe(data):
    try:
        return json.loads(data)
    except (ValueError, TypeError):
        return None
Answered By: pymen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.