加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python中将字典转换成其json字符串

发布时间:2020-12-16 19:51:07 所属栏目:Python 来源:网络整理
导读:#这是Python中的一个字典 dic = { 'str': 'this is a string','list': [1,2,'a','b'],'sub_dic': { 'sub_str': 'this is sub str','sub_list': [1,3] },'end': 'end' } //这是javascript中的一个JSON对象 json_obj = { 'str': 'this is a string','arr': [1,

#这是Python中的一个字典

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

//这是javascript中的一个JSON对象

json_obj = { 'str': 'this is a string','arr': [1,'sub_obj': { 'sub_str': 'this is sub str','end': 'end' }

实际上JSON就是Python字典的字符串表示,但是字典作为一个复杂对象是无法直接转换成定义它的代码的字符串(不能传递所以需要将其转换成字符串先),Python有一个叫simplejson的库可以方便的完成JSON的生成和解析,这个包已经包含在Python2.6中,就叫json 主要包含四个方法: dump和dumps(从Python生成JSON),load和loads(解析JSON成Python的数据类型)dump和dumps的唯一区别是dump会生成一个类文件对象,dumps会生成字符串,同理load和loads分别解析类文件对象和字符串格式的JSON

import json dic = { 'str': 'this is a string','end': 'end' } json.dumps(dic) #output: #'{"sub_dic": {"sub_str": "this is sub str","sub_list": [1,3]},"end": "end","list": [1,"a","b"],"str": "this is a string"}'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读