玩蛇网提供最新Python编程技术信息以及Python资源下载!

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格式校验工具。

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/json/7101.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年02月08日 - 20时53分50秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > JSON教程 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules