摘要:在前后端交互、数据存储、api 接口开发中,json 是最常用的数据交换格式之一。python 内置的 json 模块为我们提供了强大的支持,其中 json.loads() 和 json.dump() 是使用频率极高的两个方法。本文将带你从零掌握这两个方法的用法和常见场景,助你轻松玩转 json 数据!
一、什么是 json?
json(javascript object notation)是一种轻量级的数据交换格式,具有良好的可读性和跨平台兼容性,广泛应用于网络请求、配置文件、日志记录等场景。
python 提供了内置模块 json 来处理 json 数据,主要包含以下常用函数:
| 方法名 | 功能说明 |
|---|---|
json.loads() | 将 json 字符串 转为 python 对象 |
json.dump() | 将 python 对象 写入 json 文件 |
今天我们重点讲解的是:json.loads() 和 json.dump()。
二、json.loads():字符串转对象
1.功能
将json 格式的字符串(str)转换为 python 的原生数据类型(字典、列表、字符串、数字等)。
2.基本用法
import json
json_str = '{"name": "tom", "age": 25, "city": "beijing"}'
data_dict = json.loads(json_str)
print(data_dict) # 输出字典
print(data_dict["name"]) # 可以正常访问字段
常用参数:
object_hook:可选,指定一个函数,用于将解码后的字典转换为自定义对象。parse_float:可选,指定解析浮点数时的类型(如decimal)。
3.简单示例
import json
# json 字符串(注意使用双引号)
json_str = '{"name": "alice", "age": 30, "city": "new york"}'
# 解析为 python 字典
data = json.loads(json_str)
print(data) # {'name': 'alice', 'age': 30, 'city': 'new york'}
print(type(data)) # <class 'dict'>
print(data["name"]) # alice# json 数组字符串 json_arr = '[1, 2, 3, "hello"]' py_list = json.loads(json_arr) print(py_list) # [1, 2, 3, 'hello']
注意事项:
- 输入必须是合法的 json 字符串,否则会抛出
json.jsondecodeerror - 支持的数据类型包括:字符串、数字、布尔值、数组、对象等
三、json.dump():对象写入文件
1. 功能
将 python 对象序列化为 json 格式,并写入到文件对象(如 .json 文件)中。
2.基本用法
import json
data = {
"title": "hello world",
"content": "this is a test article.",
"author": "john"
}
with open("output.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=false, indent=4)
参数说明:
ensure_ascii=false:防止中文被转义成 unicodeindent=4:美化输出格式,缩进 4 个空格
生成的 output.json 文件内容如下:
{
"title": "hello world",
"content": "this is a test article.",
"author": "john"
}
常用参数:
obj:要序列化的 python 对象。fp:文件对象(通常由open()返回)。ensure_ascii:若为false,则非 ascii 字符(如中文)会保持原样输出(不转义为\uxxxx)。indent:缩进空格数,美化输出。sort_keys:是否按字典键排序输出。separators:自定义分隔符,如(',', ': ')。
3. 简单示例
import json
data = {
"name": "alice",
"age": 30,
"city": "new york"
}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=false)生成的 data.json 文件内容:
{
"name": "alice",
"age": 30,
"city": "new york"
}四、组合使用案例:读取并写入 json 数据
import json
# 1. 读取原始 json 文件
with open("input.json", "r", encoding="utf-8") as f:
data = json.load(f)
# 2. 修改数据内容
data["status"] = "published"
# 3. 写回新文件
with open("output.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=false, indent=4)
五、实战场景示例
场景 1:从 api 获取 json 响应并解析
import requests
import json
response = requests.get("https://api.example.com/data")
# 假设 response.text 是 json 字符串
data = json.loads(response.text)
print(data["key"])场景 2:读取配置文件
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f) # 注意这里是 json.load()(从文件读取)
print(config["database"]["host"])场景 3:写入日志或导出数据
def export_to_json(data, filename):
with open(filename, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=false)场景 4:处理 datetime 对象(自定义编码器)
from datetime import datetime
import json
class datetimeencoder(json.jsonencoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
data = {"timestamp": datetime.now()}
with open("time.json", "w") as f:
json.dump(data, f, cls=datetimeencoder)结语:掌握 json.loads() 与 json.dump(),你就掌握了数据交互的基础!
无论是爬虫、后端接口开发,还是数据分析,json 都无处不在。而 json.loads() 和 json.dump() 则是你操作 json 数据的两大利器。
到此这篇关于python中json.loads()与json.dump()玩法全解析(附实战示例)的文章就介绍到这了,更多相关python json.loads()与json.dump()区别内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论