Python 3 读写 json 文件

使用函数 json.dumps()、loads() 、json.dump()、json.load() 。

1 json.dumps() 将python对象编码成Json字符串

python 复制代码
import json

data = {
	'name':'Alice',
	'age':25,
	'gender':'F',
	'city':'北京'
}

# 1 json.dumps()	将python对象编码成Json字符串
print(type(data))
json_str = json.dumps(data)
print(type(json_str), json_str)

# ensure_ascii=True:默认输出ASCLL码,如果把这个该成False,就可以输出中文。
json_str = json.dumps(data, ensure_ascii=False)
print(type(json_str), json_str)


'''
<class 'dict'>
<class 'str'> {"name": "Alice", "age": 25, "gender": "F", "city": "\u5317\u4eac"}
<class 'str'> {"name": "Alice", "age": 25, "gender": "F", "city": "北京"}
'''

2 json.loads() 将Json字符串解码成python对象

python 复制代码
import json

# 2 json.loads()	将Json字符串解码成python对象
json_str = '{"name": "Alice", "age": 25, "gender": "F", "city": "北京"}'
data = json.loads(json_str)
print(type(data), data)


'''
<class 'dict'> {'name': 'Alice', 'age': 25, 'gender': 'F', 'city': '北京'}
'''

3 json.dump() 将python中的对象转化成json储存到文件中

python 复制代码
import json

data = {
	'name':'Alice',
	'age':25,
	'gender':'F',
	'city':'北京'
}

# 3 json.dump()	将python中的对象转化成json储存到文件中
with open('example.json', 'w', encoding='utf-8') as f:
	json.dump(data, f, ensure_ascii=False)


# example.json
'''
{"name": "Alice", "age": 25, "gender": "F", "city": "北京"}
'''

4 json.load() 将文件中的json的格式转化成python对象提取出来

python 复制代码
import json

# example.json
'''
{"name": "Alice", "age": 25, "gender": "F", "city": "北京"}
'''

# 4 json.load()	将文件中的json的格式转化成python对象提取出来
with open('example.json', 'r', encoding='utf-8') as f:
	data = json.load(f)
	print(type(data), data)


'''
<class 'dict'> {'name': 'Alice', 'age': 25, 'gender': 'F', 'city': '北京'}
'''

参考:

python的JSON用法------dumps的各种参数用法(详细)_jsondump用法-CSDN博客

json.dump()与json_dumps()区别_json.dumps-CSDN博客

Python json.dumps()函数使用解析 | w3cschool笔记

相关推荐
威联通网络存储17 小时前
某高端显示面板制造企业:基于威联通 TS-h2490FU 的 AOI 检测数据治理实践
python·制造
FreakStudio21 小时前
不用装软件!这款MicroPython浏览器 IDE :让你在手机上也能调试树莓派 Pico
python·单片机·嵌入式·电子diy·tinyml
m0_7434703721 小时前
使用Python进行PDF文件的处理与操作
jvm·数据库·python
数据科学小丫1 天前
Python 数据存储操作_数据存储、补充知识点:Python 与 MySQL交互
数据库·python·mysql
Knight_AL1 天前
Nacos 启动问题 Failed to create database ’D:\nacos\nacos\data\derby-data’
开发语言·数据库·python
查古穆1 天前
python进阶-Pydantic模型
开发语言·python
佳木逢钺1 天前
PyQt界面美化系统高级工具库:打造现代化桌面应用的完整指南
python·pyqt
工頁光軍1 天前
基于Python的Milvus完整使用案例
开发语言·python·milvus
Csvn1 天前
特殊方法与运算符重载
python
xht08321 天前
PHP vs Python:编程语言终极对决
开发语言·python·php