Verify if a String is JSON in python?

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

Leave a Comment