欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python操作json的方法实例分析

时间:2022-01-30 11:22:20|栏目:Python代码|点击:

本文实例讲述了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 "<pyshell#10>", line 1, in <module>
  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.jb51.net/code/json

JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat

在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans

更多Python相关内容感兴趣的读者可查看本站专题:《Python操作json技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

上一篇:稳扎稳打学Python之容器 可迭代对象 迭代器 生成器专题讲解

栏    目:Python代码

下一篇:python 如何用 Hypothesis 来自动化单元测试

本文标题:Python操作json的方法实例分析

本文地址:http://www.codeinn.net/misctech/191864.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有