Verify if a String is JSON in python?

后端 未结 4 546
遇见更好的自我
遇见更好的自我 2020-12-29 05:12

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

4条回答
  •  孤城傲影
    2020-12-29 06:11

    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.

提交回复
热议问题