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() 接收字符串参数。


相关推荐
Csvn1 天前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch89181 天前
Python主流框架全解析
开发语言·python
Java成神之路-1 天前
SpringMVC 响应实战指南:页面、文本、JSON 返回全流程(Spring系列13)
java·spring·json
sg_knight1 天前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财1 天前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張4081 天前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_423533991 天前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz1 天前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据1 天前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby1 天前
springboot读取配置文件
后端·python·flask