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格式校验工具。
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16