python字典和json字符串如何相互转化?

Python 的字典(dict) 和 JSON 字符串 是非常常用的数据结构和格式。Python 提供了非常简便的方法来将字典与 JSON 字符串相互转化,主要使用 json 模块中的两个函数:json.dumps()json.loads()

1. 字典转 JSON 字符串

将 Python 字典转换为 JSON 字符串使用的是 json.dumps() 函数。

示例:
python 复制代码
import json

# Python 字典
data_dict = {
    'name': 'AI',
    'type': 'Technology',
    'year': 2024
}

# 转换为 JSON 字符串
json_str = json.dumps(data_dict)
print(json_str)

输出:

python 复制代码
{"name": "AI", "type": "Technology", "year": 2024}
  • json.dumps() 参数
    • indent:可以美化输出,指定缩进级别。例如 json.dumps(data_dict, indent=4) 会生成带缩进的 JSON 字符串。
    • sort_keys=True:会将输出的 JSON 键按字母顺序排序。
    • ensure_ascii=False:用于处理非 ASCII 字符(如中文),避免转换为 Unicode 形式。

2. JSON 字符串转字典

要将 JSON 字符串转换为 Python 字典,可以使用 json.loads() 函数。

示例:
python 复制代码
import json

# JSON 字符串
json_str = '{"name": "AI", "type": "Technology", "year": 2024}'

# 转换为 Python 字典
data_dict = json.loads(json_str)
print(data_dict)

输出:

python 复制代码
{'name': 'AI', 'type': 'Technology', 'year': 2024}

3. 字典与 JSON 文件的转换

在实际项目中,可能需要将字典保存为 JSON 文件或从 JSON 文件读取字典。json 模块提供了 dump()load() 方法来处理文件的输入输出。

将字典保存为 JSON 文件:
python 复制代码
import json

data_dict = {
    'name': 'AI',
    'type': 'Technology',
    'year': 2024
}

# 保存为 JSON 文件
with open('data.json', 'w') as json_file:
    json.dump(data_dict, json_file, indent=4)
从 JSON 文件读取为字典:
python 复制代码
import json

# 从 JSON 文件中读取数据
with open('data.json', 'r') as json_file:
    data_dict = json.load(json_file)
    print(data_dict)

4. 处理特殊数据类型

在 Python 中,JSON 数据类型与 Python 数据类型基本对应,但是某些特殊类型(如 datetimeset)需要自定义处理,因为 JSON 不支持这些类型。可以通过自定义编码器来处理。

例如,处理 datetime
python 复制代码
import json
from datetime import datetime

# Python 字典包含 datetime 类型
data = {
    'name': 'AI',
    'timestamp': datetime.now()
}

# 自定义编码器
class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super(DateTimeEncoder, self).default(obj)

# 转换为 JSON 字符串
json_str = json.dumps(data, cls=DateTimeEncoder)
print(json_str)
相关推荐
IVEN_16 分钟前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮2 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling2 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮5 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽5 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健20 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers