python中将字典转换成其json字符串
作者:hebedich 时间:2023-10-16 23:46:41
#这是Python中的一个字典
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' }
//这是javascript中的一个JSON对象
json_obj = { 'str': 'this is a string', 'arr': [1, 2, 'a', 'b'], 'sub_obj': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, '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', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' } json.dumps(dic) #output: #'{"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"}'
标签:python,字典,json
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySql的事务使用与示例详解
2024-01-27 17:24:50
Django修改app名称和数据表迁移方案实现
2022-12-14 17:09:11
图像替换新技术:状态域方法[译]
2009-08-06 16:41:00
何在MySQL数据库中定义外键
2009-12-17 12:29:00
asp读取xml实例代码
2011-03-08 11:13:00
Python Pygame实战之超级炸弹人游戏的实现
2023-07-24 00:56:11
![](https://img.aspxhome.com/file/2023/3/120353_0s.jpg)
Python详细讲解图像处理的而两种库OpenCV和Pillow
2022-08-14 05:23:19
![](https://img.aspxhome.com/file/2023/3/79493_0s.png)
利用Axure封装视觉标准
2008-10-21 10:42:00
![](https://img.aspxhome.com/file/UploadPic/200810/21/20081021104738239s.jpg)
SQL Server中的执行引擎入门 图解
2012-06-06 20:08:26
PyTorch加载自己的数据集实例详解
2022-07-29 14:10:36
修改MySQL数据库中表和表中字段的编码方式的方法
2024-01-26 22:23:54
用户体验之内容篇
2010-11-05 18:21:00
![](https://img.aspxhome.com/file/UploadPic/201011/5/01-42s.jpg)
Python实现的矩阵类实例
2023-08-13 07:52:09
python基于celery实现异步任务周期任务定时任务
2021-06-14 05:20:26
![](https://img.aspxhome.com/file/2023/0/109350_0s.png)
基于Python的OCR实现示例
2021-03-05 20:58:43
django时区问题的解决
2022-06-09 10:56:45
Bootstrap Table的使用总结
2024-03-14 01:53:06
![](https://img.aspxhome.com/file/2023/9/56379_0s.png)
django DRF图片路径问题的解决方法
2023-02-05 15:25:46
![](https://img.aspxhome.com/file/2023/7/123617_0s.jpg)
JavaScript实现彩虹文字效果的方法
2024-06-05 09:34:41
ORACLE8的分区管理
2023-07-13 14:42:43