Python json读写方式和字典相互转化
作者:落日峡谷 时间:2021-03-25 05:28:19
在Python中,json指的是符合json语法格式的字符串,可以单行或者多行。
它可以方便的在使用在多种语言中,这里介绍的是在python中的字典(dict)与json字符串相互转化的方式。
1. 导入json包
import json
2. 初始化一个字典数据
dict_ = {
'name': 'Jack',
'age': 22,
'skills': ['Python', 'Java', 'C++', 'Matlab'],
'major': '计算机技术',
'english': '英语六级',
'school': 'WIT'
}
3.json.dumps(字典):将字典转为JSON字符串
# 1. json.dumps(字典):将字典转为JSON字符串,indent为多行缩进空格数,
# sort_keys为是否按键排序,ensure_ascii=False为不确保ascii,及不将中文等特殊字符转为\uXXX等
json_dict = json.dumps(dict_)
print(json_dict)
很明显中文字符被转化了,于是使用:ensure_ascii=False
# 行缩进和键值排序
json_dict_2 = json.dumps(dict_, indent=2, sort_keys=True, ensure_ascii=False)
print(json_dict_2)
3.json.loads(json串),将json字符串转化成字典
dict_from_str = json.loads(json_dict)
print(dict_from_str)
dict_from_str_2 = json.loads(json_dict_2)
print(dict_from_str_2)
4.json.dump,把字典转换成json字符串并存储在文件中,结果文件如下图:
with open("write_json.json", "w", encoding='utf-8') as f:
# json.dump(dict_, f) # 写为一行
json.dump(dict_, f, indent=2, sort_keys=True, ensure_ascii=False) # 写为多行
5.json.load,从文件打开json数据转换成字典
with open("write_json.json", encoding="utf-8") as f:
json_file = json.load(f)
print(json_file)
来源:https://www.cnblogs.com/qi-yuan-008/p/12561893.html
标签:Python,json,读写,字典
0
投稿
猜你喜欢
Django程序的优化技巧
2023-11-10 00:29:24
Python3 加密(hashlib和hmac)模块的实现
2022-07-02 08:13:52
python实现自动抢课脚本的示例代码
2022-03-12 08:16:19
利用Python判断你的密码难度等级
2021-04-10 20:46:08
pytorch加载自己的图像数据集实例
2021-09-25 12:00:49
yui3的AOP(面向切面编程)和OOP(面向对象编程)
2009-09-24 14:47:00
python多线程http压力测试脚本
2022-12-31 16:48:37
asp.net连接查询SQL数据库并把结果显示在网页上(2种方法)
2024-01-12 13:28:10
解决Pytorch中的神坑:关于model.eval的问题
2021-09-17 17:16:55
讲解SQL Server危险扩展存储删除和恢复
2008-12-09 14:30:00
Python接单的过程记录分享
2022-05-24 13:33:23
php开发微信支付获取用户地址
2023-09-07 15:12:08
Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题
2022-06-09 20:07:37
php实现生成验证码实例分享
2024-05-02 17:13:26
Python 3 使用Pillow生成漂亮的分形树图片
2022-05-03 14:53:23
go实现反转链表
2024-02-07 12:54:59
Python绘图之柱形图绘制详解
2023-08-16 16:16:49
Python Selenium Cookie 绕过验证码实现登录示例代码
2021-11-12 08:25:24
Linux下python与C++使用dlib实现人脸检测
2023-06-13 16:13:20
mysql5.7.21启动异常的修复方法
2024-01-24 20:33:16