在 Python 中,数据格式转换是非常常见的任务。我们可以使用内置的模块如 json 或者 pandas 来进行格式转换。你提到的 .jsonl 文件(JSON Lines)是每一行都是一个 JSON 对象的文件格式,而 .json 是标准的 JSON 文件格式。
任务目标
我们要从 .jsonl 文件中读取数据,并将其转换为标准的 .json 格式(通常是将多个 JSON 对象合并到一个列表中)。
数据格式说明
-
JSONL 格式:每一行是一个单独的 JSON 对象,例如:
{"name": "John", "age": 30} {"name": "Jane", "age": 25} -
目标 JSON 格式:将所有这些 JSON 对象组合成一个列表,例如:
[ {"name": "John", "age": 30}, {"name": "Jane", "age": 25} ]
示例代码
import json
# 定义输入和输出文件路径
input_file = 'data.jsonl' # 假设的.jsonl文件名
output_file = 'output.json' # 要转换为的.json文件名
# 读取 .jsonl 文件并将其转换为标准的 .json 格式
def jsonl_to_json(input_file, output_file):
data_list = []
# 逐行读取 .jsonl 文件
with open(input_file, 'r', encoding='utf-8') as infile:
for line in infile:
try:
# 将每行JSON对象解析为Python字典,并追加到列表中
data_list.append(json.loads(line.strip()))
except json.JSONDecodeError as e:
# 如果遇到解码错误,则打印警告信息
print(f"Error decoding JSON: {e}")
# 将整个列表写入到标准的 .json 文件
with open(output_file, 'w', encoding='utf-8') as outfile:
json.dump(data_list, outfile, indent=4, ensure_ascii=False)
print(f"Conversion complete! Output saved to {output_file}")
# 调用转换函数
jsonl_to_json(input_file, output_file)
代码说明
-
读取
.jsonl文件:逐行读取.jsonl文件中的每一个 JSON 对象,使用json.loads将其解析为 Python 的字典对象,并将其添加到一个列表中。 -
处理解码错误:在解析过程中,可能遇到一些不合法的 JSON 数据,
try-except块用来捕获并处理JSONDecodeError错误。 -
写入
.json文件:使用json.dump将最终的列表对象写入到.json文件中,并设置indent=4来让输出更具可读性,ensure_ascii=False确保非 ASCII 字符能够正确显示(如果有中文字符等)。
输出示例
如果 data.jsonl 文件内容为:
{"name": "John", "age": 30}
{"name": "Jane", "age": 25}
转换后的 output.json 文件内容将是:
[
{
"name": "John",
"age": 30
},
{
"name": "Jane",
"age": 25
}
]
注意事项
- 如果
.jsonl文件中存在不合法的 JSON 行,代码会跳过这些行并打印错误信息。 - 如果文件较大,可能需要使用生成器来逐行处理,避免将所有数据一次性加载到内存中。
这样可以将 .jsonl 格式的数据转换为标准的 .json 文件格式。

被折叠的 条评论
为什么被折叠?



