Python3中字典、列表与JSON对象互转详解

Finn
Finn
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍Python3中利用json模块实现字典、列表与JSON对象相互转换的方法。通过json.dumps()将Python数据结构编码为JSON字符串,对应PHP的json_encode();使用json.loads()将JSON字符串解码为Python对象,对应PHP的json_decode()。文章提供完整代码示例及运行结果,并推荐相关在线JSON工具供开发者参考。

本文通过具体实例,详细讲解如何在Python3中实现字典、列表与JSON对象之间的相互转换,供读者参考学习。

在Python3中,可以通过内置的json模块来方便地处理JSON数据。

使用json.dumps()函数可对Python数据结构进行编码,生成JSON字符串,其功能类似于PHP中的json_encode()函数。

使用json.loads()函数可对JSON字符串进行解码,还原为Python对象,其功能类似于PHP中的json_decode()函数。

示例文件名为test.py,具体代码如下所示。

#!/usr/bin/python3
import json
#python字典类型转换为json对象
data = {
  'id' : 1,
  'name' : 'test1',
  'age' : '1'
}
data2 = [{
  'id' : 1,
  'name' : 'test1',
  'age' : '1'
},{
  'id' : 2,
  'name' : 'test2',
  'age' : '2'
}]
json_str = json.dumps(data)
print ("python原始数据:", repr(data))
print ("json对象:", json_str)
json_str2 = json.dumps(data2)
print ("python原始数据:", repr(data2))
print ("json对象:", json_str2)
# 将json对象转换为python字典
data3 = json.loads(json_str)
print ("data3['name']: ", data3['name'])
print ("data3['age']: ", data3['age'])

运行脚本后的输出结果如下。

[root@mail pythonCode]# python3 test.py python原始数据: {'id': 1, 'name': 'test1', 'age': '1'} json对象: {"id": 1, 'name': 'test1', 'age': '1'} python原始数据: [{'id': 1, 'name': 'test1', 'age': '1'}, {'id': 2, 'name': 'test2', 'age': '2'}] json对象: [{"id": 1, 'name': 'test1', 'age': '1'}, {"id": 2, 'name': 'test2', 'age': '2'}] data3['name']: test1 data3['age']: 1

此外,关于JSON数据的处理,以下推荐几款实用的在线JSON工具,供读者在实际开发中参考使用:

在线JSON代码检验、美化及格式化工具: http://tools.jb51.net/code/json

JSON在线格式化工具: http://tools.jb51.net/code/jsonformat

在线XML与JSON互相转换工具: http://tools.jb51.net/code/xmljson

json代码在线格式化、美化、压缩、编辑及转换工具: http://tools.jb51.net/code/jsoncodeformat

在线json压缩与转义工具: http://tools.jb51.net/code/json_yasuo_trans

对Python其他功能感兴趣的读者,可进一步查阅本站专题:《Python操作json技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》以及《Python文件与目录操作技巧汇总》。

希望本文所述的转换方法对读者的Python编程实践有所帮助。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表