jsonl文件介绍
- 什么是 jsonl 文件
- 文件结构
- 读取jsonl文件
- 写入jsonl文件
什么是 jsonl 文件
jsonl(json lines)是一种文件格式,其中每一行都是一个单独的 json 对象。与常规的 json文件不同,jsonl文件在处理大量数据时具有优势,因为它能够逐行读取和处理数据,而不需要一次加载整个文件。
文件结构
jsonl文件的结构非常简单,每行都是一个有效的json对象,行与行之间没有逗号或其他分隔符。例如:
{"name": "Alice", "age": 30, "city": "New York"}
{"name": "Bob", "age": 25, "city": "San Francisco"}
{"name": "Charlie", "age": 35, "city": "Los Angeles"}
读取jsonl文件
import json
with open('data.jsonl', 'r', encoding='utf-8') as file:
for line in file:
data = json.loads(line)
print(data)
写入jsonl文件
import json
data_list = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "San Francisco"},
{"name": "Charlie", "age": 35, "city": "Los Angeles"}
]
with open('data.jsonl', 'w', encoding='utf-8') as file:
for data in data_list:
file.write(json.dumps(data) + '\n')