Verify if a String is JSON in python?

后端 未结 4 569
遇见更好的自我
遇见更好的自我 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:04

    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
    

提交回复
热议问题