The standard json library provides doesn’t have a check json is valid function. I’ve done a bit of researching and it turns out the best approach to check if a json text is to try-except with json.loads.
I came up with a generic solution to this problem which I think you’ll like.
lets start from the beginning - probably most of us will write something like that:
def is_valid_json(text): |
that’s fine, but it’s not to efficient. take a look at the following snippet:
text = "{'foo':'bar'}" |
that’s a bit ugly, right? we’re forced to load the text twice. a better solution might be:
def safe_loads(text): |
that’s great, but not generic at all. it only works for loading json text!:
class SafeInvocator(object): |
the usage is pretty simple -> if you want to safely invoke a method from the json module, all you need to do is:
safe_json = SafeInvocator(json) |