Joey Blake Joey Blake - 1 year ago 125
Python Question

How do I check if a string is valid JSON in Python?

In Python, is there a way to check if a string is valid JSON before trying to parse it?

For example working with things like the Facebook Graph API, sometimes it returns JSON, sometimes it could return an image file.

Answer Source

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.