Verify if a String is JSON in python?

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

    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
    

提交回复
热议问题