Python轻松搞定:数据转换为JSON格式的实用指南**
在当今数据驱动的世界中,JSON(JavaScript Object Notation)因其轻量级、易读、易解析以及与语言无关的特性,已成为数据交换的事实标准,Python作为一门功能强大的编程语言,提供了内置模块来轻松处理JSON数据,本文将详细介绍如何使用Python将各种数据类型转换为JSON格式,并涵盖常见场景和注意事项。
为什么选择JSON?
在开始之前,简单回顾一下JSON为何如此流行:
- 轻量级:相比XML,JSON更简洁,传输效率更高。
- 易读易写:格式清晰,人类和机器都易于理解。
- 语言无关:几乎所有编程语言都支持JSON的解析和生成。
- 结构灵活:可以表示复杂的数据结构,如嵌套对象和数组。
Python处理JSON的利器:json模块
Python内置了json模块,它提供了对JSON数据编码(序列化)和解码(反序列化)的支持,我们将重点关注其中的编码(序列化)功能,即将Python对象转换为JSON字符串。
核心函数:json.dumps()
json.dumps()函数是“dump string”的缩写,用于将Python对象编码成JSON格式的字符串。
基本语法:
import json json_string = json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False)
常用参数:
obj: 要编码的Python对象(如字典、列表、元组、字符串、数字、布尔值、None)。indent: 指定缩进字符串,以美化输出(使JSON更易读),通常是一个整数(表示缩进空格数)或字符串(如"\t")。ensure_ascii: 如果为True(默认),输出将确保所有非ASCII字符都被转义为\uXXXX序列,如果为False,则允许非ASCII字符直接输出(适用于处理中文等非英文字符)。sort_keys: 如果为True,则输出JSON对象的键将按字母顺序排序。
示例1:将基本数据类型转换为JSON
Python的基本数据类型可以直接转换为JSON:
import json
# Python字典 -> JSON对象
python_dict = {"name": "张三", "age": 30, "city": "北京"}
json_str_dict = json.dumps(python_dict)
print("字典转JSON字符串:")
print(json_str_dict) # 输出: {"name": "张三", "age": 30, "city": "北京"}
# Python列表 -> JSON数组
python_list = [1, 2, "hello", True, None]
json_str_list = json.dumps(python_list)
print("\n列表转JSON字符串:")
print(json_str_list) # 输出: [1, 2, "hello", true, null]
# Python元组 -> JSON数组 (元组会被转换为列表)
python_tuple = (1, 2, 3)
json_str_tuple = json.dumps(python_tuple)
print("\n元组转JSON字符串:")
print(json_str_tuple) # 输出: [1, 2, 3]
# Python字符串 -> JSON字符串
python_str = "Hello, Python!"
json_str_str = json.dumps(python_str)
print("\n字符串转JSON字符串:")
print(json_str_str) # 输出: "Hello, Python!"
# Python数字 -> JSON数字
python_num = 123.45
json_str_num = json.dumps(python_num)
print("\n数字转JSON字符串:")
print(json_str_num) # 输出: 123.45
# Python布尔值 -> JSON布尔值
python_bool = True
json_str_bool = json.dumps(python_bool)
print("\n布尔值转JSON字符串:")
print(json_str_bool) # 输出: true
# Python None -> JSON null
python_none = None
json_str_none = json.dumps(python_none)
print("\nNone转JSON字符串:")
print(json_str_none) # 输出: null
示例2:美化JSON输出(缩进和排序)
当需要生成易于阅读的JSON时,可以使用indent和sort_keys参数:
import json
data = {
"name": "李四",
"age": 25,
"hobbies": ["reading", "traveling"],
"address": {
"street": "人民路123号",
"city": "上海"
}
}
# 不带缩进和排序
json_str_basic = json.dumps(data)
print("基本JSON输出:")
print(json_str_basic)
# 带缩进(4个空格)和键排序
json_str_pretty = json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False)
print("\n美化后的JSON输出(ensure_ascii=False显示中文):")
print(json_str_pretty)
输出:
基本JSON输出:
{"name": "李四", "age": 25, "hobbies": ["reading", "traveling"], "address": {"street": "人民路123号", "city": "上海"}}
美化后的JSON输出(ensure_ascii=False显示中文):
{
"address": {
"city": "上海",
"street": "人民路123号"
},
"age": 25,
"hobbies": [
"reading",
"traveling"
],
"name": "李四"
}
示例3:处理嵌套数据结构
JSON的强大之处在于支持嵌套对象和数组,Python的字典和列表可以完美对应:
import json
complex_data = {
"students": [
{"id": 1, "name": "王五", "scores": [85, 90, 78]},
{"id": 2, "name": "赵六", "scores": [92, 88, 95]}
],
"class_name": "高三(1)班"
}
json_str_complex = json.dumps(complex_data, indent=2, ensure_ascii=False)
print("嵌套数据转JSON:")
print(json_str_complex)
示例4:将JSON数据写入文件
json.dumps()生成的是字符串,如果要将数据持久化到文件,可以使用json.dump()函数(注意没有s),它直接将对象写入文件流。
import json
data_to_write = {
"product": "智能手机",
"price": 4999,
"in_stock": True
}
# 写入JSON文件
with open("product.json", "w", encoding="utf-8") as f:
json.dump(data_to_write, f, indent=4, ensure_ascii=False)
print("数据已成功写入product.json文件")
执行后,会生成一个名为product.json的文件,内容如下:
{
"product": "智能手机",
"price": 4999,
"in_stock": true
}
Python对象与JSON类型的对应关系
了解Python对象与JSON类型的对应关系非常重要:
| Python类型 | JSON类型 | 说明 |
|---|---|---|
dict |
object | JSON对象,键必须是字符串 |
list, tuple |
array | JSON数组,元组会被转换为列表 |
str |
string | JSON字符串 |
int, float |
number | JSON数字 |
True |
true | JSON布尔值真 |
False |
false | JSON布尔值假 |
None |
null | JSON空值 |
常见问题与注意事项
-
TypeError: Object of type XXX is not JSON serializable 当尝试序列化Python中不支持的基本类型以外的对象时(例如自定义类的实例、日期时间对象datetime等),会抛出此错误。 解决方案:-
default参数:提供一个函数,该函数知道如何将不可序列化的对象转换为可序列化的形式。from datetime import datetime def datetime_handler(obj): if isinstance(obj, datetime): return obj.isoformat() raise TypeError(f"Object of type {type(obj)} is not JSON serializable") data_with_datetime = {"event": "会议", "time": datetime.now()} json_str = json.dumps(data_with_datetime, default=datetime_handler, ensure_ascii=False) print(json_str) -
转换为字典:对于自定义类,可以定义一个方法返回字典表示,然后序列化该字典。
-
-
中文字符显示为
\uXXXX这是ensure_ascii=True(默认)的行为,如果希望直接显示中文字符,需要设置ensure_ascii=False,如前面的示例所示。 -
JSON对象键必须是字符串 Python字典的键可以是多种可哈希类型,但JSON对象的



还没有评论,来说两句吧...