1 python判断一个字符串是否为json

代码:

import json as json

def str_is_json_format(input_str):
    if isinstance(input_str,str):
        try:
            json.loads(input_str,encoding='utf-8')
        except ValueError:
            return False
        return True
    else:
        return False

if __name__ == '__main__':
    print(str_is_json_format('{"a":1,"b":2}'))
    print(str_is_json_format('{"a":}'))
    print(str_is_json_format('{"":1}'))

运行结果如下:

True
False
True