9.6 JSON 基本操作


文章目录

  • 前言
  • [一、JSON与Python json模块简介](#一、JSON与Python json模块简介)
  • 二、json模块常用方法
    • [2.1 dumps:将 Python 对象转为 JSON 字符串](#2.1 dumps:将 Python 对象转为 JSON 字符串)
    • [2.2 dump:将 Python 对象直接写入文件](#2.2 dump:将 Python 对象直接写入文件)
    • [2.3 loads:将 JSON 字符串转为 Python 对象](#2.3 loads:将 JSON 字符串转为 Python 对象)
    • [2.4 load:从文件类对象直接读取并转换](#2.4 load:从文件类对象直接读取并转换)

前言

本文主要介绍Python json模块简介及常用方法。


一、JSON与Python json模块简介

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,结构清晰、易于阅读和编写,能够有效提升网络传输效率。Python 内置的 json 模块提供了一系列方法,用于处理 JSON 格式数据的编码与解码。

二、json模块常用方法

json 模块主要包含 dump、dumps、load、loads 四种核心方法,用于实现 JSON 数据与 Python 对象之间的相互转换。

2.1 dumps:将 Python 对象转为 JSON 字符串

dumps() 方法可将 Python 对象转换为 JSON 格式字符串。例如,将字典转换为 JSON 字符串:

python 复制代码
python
import json

data = {'id': '001', 'name': '张三', 'age': '20'}
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)

输出结果:

bash 复制代码
text
{"id": "001", "name": "张三", "age": "20"}

若需格式化输出,可添加参数控制格式:

python 复制代码
python
json_str = json.dumps(
    data, 
    ensure_ascii=False, 
    sort_keys=True, 
    indent=4, 
    separators=(',', ': ')
)

输出结果:

bash 复制代码
json
{
    "age": "20",
    "id": "001",
    "name": "张三"
}

Python 对象与 JSON 类型对应关系

Python JSON
dict object
list, tuple array
str string
int, float, 枚举类 number
True true
False false
None null

将 JSON 字符串写入文件

python 复制代码
python
with open('test.json', 'w', encoding='utf-8') as f:
    f.write(json_str)

2.2 dump:将 Python 对象直接写入文件

dump() 方法可将 Python 对象序列化为 JSON 格式并直接写入文件类对象:

python 复制代码
python
with open('test.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=4, ensure_ascii=False)

该方法适用于直接将数据保存为 JSON 文件的场景。若需将数据转换为字符串(如存入数据库),则应使用 dumps()。

2.3 loads:将 JSON 字符串转为 Python 对象

loads() 方法用于将 JSON 格式字符串转换为 Python 对象:

python 复制代码
python
json_str = '{"id": "001", "name": "张三", "age": "20"}'
data_dict = json.loads(json_str)
print(data_dict)

输出结果:

bash 复制代码
text
{'id': '001', 'name': '张三', 'age': '20'}

JSON 类型与 Python 对象对应关系

JSON Python
object dict
array list
string str
number(int) int
number (real) float
true True
false False
null None

读取 JSON 文件并转换为 Python 对象

python 复制代码
python
with open('test.json', encoding='utf-8') as f:
    data = f.read()
    print(json.loads(data))

2.4 load:从文件类对象直接读取并转换

load() 方法可直接从文件类对象中读取数据并转换为 Python 对象:

python 复制代码
python
with open('test.json', encoding='utf-8') as f:
    data_dict = json.load(f)
    print(data_dict)

该方法与 loads() 的区别在于:load() 接收文件对象作为参数,而 loads() 接收字符串参数。


相关推荐
wangchunyu1146 小时前
JAVA CompletableFuture异步编程实战
java·开发语言·python
2501_944521598 小时前
Immer 跨端三方库仓颉适配全流程
python·eclipse·django
信誓旦旦的程序猿8 小时前
【Python量化实战宝典 #26】止损与回撤控制手册:移动止损、最大回撤(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
2501_944521598 小时前
Deepmerge 跨端三方库仓颉适配全流程
java·python·eclipse·github
Patrick在香港8 小时前
同一行 strftime,两台机器跑出两种日期
python·datetime·时区·locale·日期处理
2601_967987378 小时前
用Python+OpenCV+YOLO写个游戏脚本:从自动瞄准到自动采集的保姆级教程
python·opencv·yolo·目标检测·游戏自动化
meiying88388 小时前
快递单号批量查询Python脚本:从手动到自动化的完整实现
开发语言·python·自动化
人工智能导论实践课9 小时前
【GUI桌面开发3】PyCharm配置外部工具
ide·python·pycharm
一千柯橘9 小时前
LangChain 的实时输出处理: stream_events 和 Streaming
python·langchain·agent
贾公子9 小时前
图片 AIGC 检测接入实战——URL 与 Base64 的取舍、体积校验与「你送过去的可能不是那张图」
python·aigc