python操作json的方法有
json.dumps
——将json对象(字典)转换为字符串对象
json.loads
——将字符串对象转换为json对象(字典)
如果定义json对象
jsonstring1={"results":[{"id":"1","name":"u9ed8u8ba4u5206u7ec4","policy":"4","timer_scan_setting":"{"last":"10.29.13","setting":"fulldisk","type":"day","hour":"13"}"}, {"id":"2","name":"u6d4bu8bd5u7684","policy":"1","timer_scan_setting":"{"last":"10.29.15","setting":"fulldisk","type":"day","hour":"15"}"},{"id":"4","name":"u4ea7u54c1u7ec4","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":"u9ed8u8ba4u5206u7ec4","policy":"4","timer_scan_setting":"{"last":"10.29.13","setting":"fulldisk","type":"day","hour":"13"}"}, {"id":"2","name":"u6d4bu8bd5u7684","policy":"1","timer_scan_setting":"{"last":"10.29.15","setting":"fulldisk","type":"day","hour":"15"}"},{"id":"4","name":"u4ea7u54c1u7ec4","policy":"3","timer_scan_setting":"{"last":"10.8.15","setting":"disable"}"}]}'''
这个只是对上面的json对象加了三引号转为一个字符串,所以理论上可以直接loads之后就按json操作
json.loads(jsonstring2)
但是实际却报错了,原因是因为大括号前后的双引号没有去掉,网上很多在线的json格式化工具对于这些双引号不会报错,但是python会,而定义json对象时加了双引号操作却没报错,是因为不加里面的内容会被转义,所以千万不能完全相信网上的json格式校验工具。
总结
【相关推荐】
1. Python免费视频教程
2. Python基础入门教程
3. Python面向对象视频教程
声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。TEL:177 7030 7066 E-MAIL:11247931@qq.com