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

相关推荐
IT知识分享10 分钟前
从零开发在线简繁转换工具:OpenCC 实战、避坑经验与方案选型
javascript·python
lunzi_082615 分钟前
【学习笔记】《Python编程 从入门到实践》第8章:函数定义、参数传递与模块导入
笔记·python·学习
杨运交32 分钟前
[030][Web模块]Spring Boot 验证与 OpenAPI 集成实战:从校验规则到文档生成
前端·spring boot·python
培培说证1 小时前
2026财务岗位如何快速提升自身能力
python
努力攻坚操作系统1 小时前
编程语言编译运行机制对比:C / Java / Python
java·c语言·python
godspeed_lucip1 小时前
LLM和Agent——专题6:Multi Agent 入门(5)
人工智能·python
Metaphor6922 小时前
使用 Python 给 PDF 设置背景色或背景图
数据库·python·pdf
郝亚军2 小时前
如何让pycharm-2026.1.2顶部菜单栏固定显示在最上端
python
怪兽学LLM3 小时前
LeetCode 438 找到字符串中所有字母异位词(Python 固定滑动窗口+字符计数解法)
python·算法·leetcode