Python操作json的方法实例分析 本文实例讲述了Python操作json的方法。分享给大家供大家参考,具体如下: python中对json操作方法有两种,解码loads()和编码dumps() 简单来说: import json dicts = json.loads() #loads()方法,将json串解码为python对象,字典 json = json.dumps(dicts) #dumps()方法,将python字典编码为json串 简单例子: >>> import json >>> dicts = {'name':'test','type':[{'happy':'fish'},{'sad':'man'}]} #python的字典 >>> print(dicts.keys()) #python的字典可以通过内置的字典方法操作keys 和values dict_keys(['type', 'name']) >>> print(dicts['name']) test >>> print(dicts['type'][0]['happy']) fish >>> print(dicts['type'][1]['sad']) man >>> j = json.dumps(dicts) #通过dumps()方法,将python字典编码为json串 >>> j '{"type": [{"happy": "fish"}, {"sad": "man"}], "name": "test"}' >>> print(j['name']) #json不能通过字典方法获取keys 和 values了。 Traceback (most recent call last): File "", line 1, in print(j['name']) TypeError: string indices must be integers 更多的信息,可以参考python内部的json文档: python>>> help(json) 如下图所示: 或者官方文档: http://docs.python.org/library/json.html#module-json PS:这里再为大家推荐几款比较实用的json在线工具供大家参考使用: 在线JSON代码检验、检验、美化、格式化工具: http://tools.zwyuanma.com/code/json JSON在线格式化工具: http://tools.zwyuanma.com/code/jsonformat 在线XML/JSON互相转换工具: http://tools.zwyuanma.com/code/xmljson json代码在线格式化/美化/压缩/编辑/转换工具: http://tools.zwyuanma.com/code/jsoncodeformat 在线json压缩/转义工具: http://tools.zwyuanma.com/code/json_yasuo_trans 更多Python相关内容感兴趣的读者可查看本站专题:《Python操作json技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》 希望本文所述对大家Python程序设计有所帮助。