python字典转json

在Python中,你可以使用内置的json模块来轻松地将字典转换为JSON格式的字符串。下面是一个简单的示例:

python 复制代码
import json

# 创建一个字典
data_dict = {
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

# 使用json.dumps()方法将字典转换为JSON字符串
json_str = json.dumps(data_dict)

# 打印JSON字符串
print(json_str)

运行上面的代码,你会得到以下输出:

json 复制代码
{"name": "John Doe", "age": 30, "city": "New York"}

这就是一个JSON格式的字符串。如果你想让输出的JSON字符串更易读(比如带有缩进和换行符),你可以给json.dumps()方法传递一个额外的参数indent,它表示缩进的空格数:

python 复制代码
json_str_pretty = json.dumps(data_dict, indent=4)
print(json_str_pretty)

运行上面的代码,你会得到以下更易读的输出:

json 复制代码
{
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}
相关推荐
悟空爬虫13 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派13 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风15 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户8356290780511 天前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon1 天前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly1 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程1 天前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly1 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风2 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python