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
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([{}])
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, e:
pass # invalid json
else:
pass # valid json
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
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.