当前位置:首页 >> 脚本专栏

python中字符串类型json操作的注意事项

python操作json的方法有

json.dumps——将json对象(字典)转换为字符串对象

json.loads——将字符串对象转换为json对象(字典)

如果定义json对象

jsonstring1={"results":[{"id":"1","name":"\u9ed8\u8ba4\u5206\u7ec4","policy":"4","timer_scan_setting":"{\"last\":\"10.29.13\",\"setting\":\"fulldisk\",\"type\":\"day\",\"hour\":\"13\"}"},
{"id":"2","name":"\u6d4b\u8bd5\u7684","policy":"1","timer_scan_setting":"{\"last\":\"10.29.15\",\"setting\":\"fulldisk\",\"type\":\"day\",\"hour\":\"15\"}"},{"id":"4","name":"\u4ea7\u54c1\u7ec4","policy":"3","timer_scan_setting":"{\"last\":\"10.8.15\",\"setting\":\"disable\"}"}]}

可以直接按json操作,比如

print jsonstring1.keys()
print jsonstring1['results'][0]['policy']

也可以转个360度再操作

jsonstring1=json.dumps(jsonstring1)
jsonstring1=json.loads(jsonstring1)
print jsonstring1.keys()
print jsonstring1['results'][0]['policy']

但是如果定义字符串对象就要小心了

jsonstring2='''{"results":[{"id":"1","name":"\u9ed8\u8ba4\u5206\u7ec4","policy":"4","timer_scan_setting":"{\"last\":\"10.29.13\",\"setting\":\"fulldisk\",\"type\":\"day\",\"hour\":\"13\"}"},
{"id":"2","name":"\u6d4b\u8bd5\u7684","policy":"1","timer_scan_setting":"{\"last\":\"10.29.15\",\"setting\":\"fulldisk\",\"type\":\"day\",\"hour\":\"15\"}"},{"id":"4","name":"\u4ea7\u54c1\u7ec4","policy":"3","timer_scan_setting":"{\"last\":\"10.8.15\",\"setting\":\"disable\"}"}]}'''

这个只是对上面的json对象加了三引号转为一个字符串,所以理论上可以直接loads之后就按json操作

json.loads(jsonstring2)

但是实际却报错了,原因是因为大括号前后的双引号没有去掉,网上很多在线的json格式化工具对于这些双引号不会报错,但是python会,而定义json对象时加了双引号操作却没报错,是因为不加里面的内容会被转义,所以千万不能完全相信网上的json格式校验工具。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。