前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python的JSON与字典区别

python的JSON与字典区别

作者头像
py3study
发布2020-01-06 15:32:49
6440
发布2020-01-06 15:32:49
举报
文章被收录于专栏:python3python3

在python中,字典的输出内容跟json格式内容一样,但是字典的格式是字典,json的格式是字符串,所以在传输的时候(特别是网页)要转换使用。

重要函数

  • 编码:把一个Python对象编码转换成Json字符串   json.dumps()
  • 解码:把Json格式字符串解码转换成Python对象   json.loads()
代码语言:javascript
复制
In [1]: import json

In [2]: dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' }

In [3]: type(dic)
Out[3]: dict

In [5]: json_obj=json.dump(dic)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-1959d613a6c1> in <module>()
----> 1 json_obj=json.dump(dic)

TypeError: dump() takes at least 2 arguments (1 given)

In [6]: json_obj=json.dumps(dic)

In [8]: type(json_obj)
Out[8]: str

In [9]: print json_obj
{"sub_dic": {"sub_str": "this is sub str", "sub_list": [1, 2, 3]}, "end": "end", "list": [1, 2, "a", "b"], "str": "this is a string"}

In [10]: dic1=json.loads(json_obj)

In [11]: type(dic1)
Out[11]: dict

In [12]: print dic1
{u'end': u'end', u'list': [1, 2, u'a', u'b'], u'sub_dic': {u'sub_str': u'this is sub str', u'sub_list': [1, 2, 3]}, u'str': u'this is a string'}

In [13]: print dic
{'sub_dic': {'sub_str': 'this is sub str', 'sub_list': [1, 2, 3]}, 'end': 'end', 'list': [1, 2, 'a', 'b'], 'str': 'this is a string'}

参考:https://docs.python.org/dev/library/json.html

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 在python中,字典的输出内容跟json格式内容一样,但是字典的格式是字典,json的格式是字符串,所以在传输的时候(特别是网页)要转换使用。
  • 重要函数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档