在实际工做中,有时候须要对判断字符串是否为合法的json格式html
解决方法使用json.loads,这样更加符合‘Pythonic’写法json
代码示例:post
Python import json def is_json(myjson): try: json_object = json.loads(myjson) except ValueError, e: return False return True
运行代码编辑模式复制折叠
输出结果:code
Python 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 print is_json('{"age":100 }') #prints True print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True
本段代码来自 http://www.chenxm.cc/post/460...htm