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

相关推荐
青 春 记 忆7 小时前
Dify Docker Compose 通用无损升级指南:从备份、双版本预演到切换与回滚
运维·人工智能·python·docker·容器
GlueNa2SiO38 小时前
03-Flask模板引擎Jinja2详解
笔记·python·flask
临沂GEO10 小时前
GEO搜索优化科普|正规地理位置流量运营入门指南
大数据·人工智能·python·流量运营
葡萄城技术团队10 小时前
如何通过 JSON 数据源 / Web API 快速构建轻量级报表(Report)?
前端·json·原型模式
大模型码小白10 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
荷蒲11 小时前
【小白量化Qbuddy】利用AI学习中文Python
人工智能·python·学习
数据狐(Datafox)13 小时前
京东商品列表API技术解析与落地应用(含标准 JSON 示例)
java·大数据·前端·人工智能·python·数据分析·json
量化吞吐机13 小时前
2026年下半年手工交易规则走向量化表达,产品该先接住哪一步
人工智能·python
Metaphor69214 小时前
使用 Python 读取和删除 Excel 文件属性
python·excel
迷迭香yy14 小时前
Python构建转融券多空识别系统从接口到因子的全流程 IG50免费开源股票数据API接口
开发语言·python·开源