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笔记

相关推荐
小九九的爸爸2 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学3 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田19 小时前
Pydantic校验配置文件
python
hboot19 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉