Python如何将List转换成JSON:全面指南与实用技巧
在Python开发中,处理数据格式转换是常见需求,尤其是将List(列表)转换为JSON(JavaScript Object Notation)格式,JSON因其轻量级、易读的特性,成为跨语言数据交换的标准格式之一,本文将详细介绍Python中将List转换为JSON的多种方法,包括内置模块的使用、自定义序列化技巧,以及常见问题的解决方案,帮助开发者高效完成数据转换任务。
使用json模块:最基础与常用的方法
Python内置的json模块提供了将Python对象序列化为JSON格式字符串的功能,是处理JSON转换的首选工具,对于List转JSON,核心函数是json.dumps()( dumps = dump string,即“转储为字符串”)。
基本语法与示例
json.dumps()的基本语法如下:
import json json_str = 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对象(如List),indent参数用于控制缩进(使JSON更易读),ensure_ascii参数控制是否将非ASCII字符转义为\u形式。
示例1:简单List转JSON
import json # 定义一个普通List my_list = [1, "apple", True, None, 3.14] # 转换为JSON字符串 json_str = json.dumps(my_list) print(json_str) # 输出: [1, "apple", true, null, 3.14]
示例2:带缩进的格式化JSON
通过indent参数,可以让输出的JSON字符串更具可读性(适合调试或配置文件):
import json
complex_list = [
{"name": "Alice", "age": 25, "hobbies": ["reading", "running"]},
{"name": "Bob", "age": 30, "hobbies": ["gaming", "coding"]}
]
# 使用indent=4格式化输出
formatted_json = json.dumps(complex_list, indent=4)
print(formatted_json)
输出结果:
[
{
"name": "Alice",
"age": 25,
"hobbies": [
"reading",
"running"
]
},
{
"name": "Bob",
"age": 30,
"hobbies": [
"gaming",
"coding"
]
}
]
处理非ASCII字符(中文、特殊符号等)
默认情况下,json.dumps()会将非ASCII字符(如中文)转义为\u形式。
import json chinese_list = ["你好", "世界"] json_str = json.dumps(chinese_list) print(json_str) # 输出: ["\u4f60\u597d", "\u4e16\u754c"]
若希望保留原始非ASCII字符(直接输出中文),可设置ensure_ascii=False:
json_str = json.dumps(chinese_list, ensure_ascii=False) print(json_str) # 输出: ["你好", "世界"]
处理复杂List(嵌套List、字典、自定义对象等)
(1)嵌套List与字典
json模块可以直接处理嵌套的List和字典,无需额外操作:
import json
nested_list = [
[1, 2, 3],
{"a": 10, "b": 20},
[4, {"c": 30}]
]
json_str = json.dumps(nested_list, indent=2)
print(json_str)
输出:
[
[
1,
2,
3
],
{
"a": 10,
"b": 20
},
[
4,
{
"c": 30
}
]
]
(2)自定义对象序列化
如果List中包含自定义类的对象,直接使用json.dumps()会报错(TypeError: Object of type X is not JSON serializable),此时需要通过default参数指定序列化方法,或为自定义类实现default()方法(作为json模块的序列化函数)。
方法1:使用default参数
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 创建包含自定义对象的List
people = [Person("Alice", 25), Person("Bob", 30)]
# 定义序列化函数
def serialize_person(obj):
if isinstance(obj, Person):
return {"name": obj.name, "age": obj.age}
raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")
# 使用default参数调用
json_str = json.dumps(people, default=serialize_person, indent=2)
print(json_str)
输出:
[
{
"name": "Alice",
"age": 25
},
{
"name": "Bob",
"age": 30
}
]
方法2:为自定义类实现__dict__和default()(更优雅)
通过为自定义类实现__dict__方法,直接返回对象的字典表示,简化序列化:
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __dict__(self):
return {"name": self.name, "age": self.age}
people = [Person("Alice", 25), Person("Bob", 30)]
json_str = json.dumps(people, default=lambda x: x.__dict__, indent=2)
print(json_str)
输出与方法1一致。
将JSON写入文件(json.dump())
如果不仅需要将List转换为JSON字符串,还要将其保存到文件中,可以使用json.dump()( dump = dump to file,即“转储到文件”)。
基本语法
import json json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False)
fp是文件对象(需以写入模式打开)。
示例
import json
data = [
{"product": "iPhone", "price": 9999},
{"product": "MacBook", "price": 12999}
]
# 写入JSON文件(使用with语句自动管理文件资源)
with open("products.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
print("JSON文件已生成:products.json")
生成的 原因:List中包含Python内置JSON不支持的对象(如自定义类、日期时间等)。 原因:JSON文件写入时未指定编码格式,导致非ASCII字符无法处理。 Python的 使用products.json
[
{
"product": "iPhone",
"price": 9999
},
{
"product": "MacBook",
"price": 12999
}
]
常见问题与解决方案
错误:
TypeError: Object of type X is not JSON serializable
解决:通过default参数指定序列化函数,或为对象实现__dict__方法(如前文“自定义对象序列化”部分)。错误:
UnicodeEncodeError: 'ascii' codec can't encode characters
解决:打开文件时明确指定encoding="utf-8"(如open("file.json", "w", encoding="utf-8"))。如何处理日期时间对象?
datetime对象无法直接序列化为JSON,需自定义转换逻辑:import json
from datetime import datetime
def serialize_datetime(obj):
if isinstance(obj, datetime):
return obj.isoformat() # 转换为ISO格式字符串(如"2023-10-01 12:00:00")
raise TypeError("Type not serializable")
data = [datetime(2023, 10, 1, 12, 0, 0), "today"]
json_str = json.dumps(data, default=serialize_datetime)
print(json_str) # 输出: ["2023-10-01T12:00:00", "today"]
如何控制JSON的键排序?
sort_keys=True参数,可以让输出的JSON键按字母顺序排序(适合需要稳定格式的情况):
import json
data = {"b": 2, "a": 1, "c": 3}
json_str = json.dumps(data, sort_keys=True)
print(json_str) # 输出: {"a": 1



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