python json jsonl 的用法详解

python json jsonl 的用法详解

JSON

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛用于在客户端和服务器之间传输数据。以下是 Python 中使用 JSON 的一些常见用法:

1. 将 Python 对象转换为 JSON 字符串

使用 json.dumps() 函数将 Python 对象(如字典、列表等)转换为 JSON 字符串。

import json# Python 字典data = { "name": "Alice", "age": 30, "city": "New York", "skills": ["Python", "Machine Learning"]}# 转换为 JSON 字符串json_str = json.dumps(data)print(json_str)

输出示例:

{ name : Alice , age : 30, city : New York , skills : [ Python , Machine Learning ]}

2. 将 JSON 字符串解析为 Python 对象

使用 json.loads() 函数将 JSON 字符串解析为 Python 对象(如字典、列表等)。

json_str = '{"name": "Alice", "age": 30, "city": "New York", "skills": ["Python", "Machine Learning"]}'# 将 JSON 字符串解析为 Python 字典data = json.loads(json_str)print(data)

输出示例:

{ name : Alice , age : 30, city : New York , skills : [ Python , Machine Learning ]}

3. 将 Python 对象写入 JSON 文件

使用 json.dump() 函数将 Python 对象写入到 JSON 文件中。

import jsondata = { "name": "Alice", "age": 30, "city": "New York", "skills": ["Python", "Machine Learning"]}# 将 Python 对象写入 JSON 文件with open('data.json', 'w') as json_file: json.dump(data, json_file)

4. 从 JSON 文件读取数据

使用 json.load() 函数从 JSON 文件中读取数据并解析为 Python 对象。

import json# 从 JSON 文件读取数据with open('data.json', 'r') as json_file: data = json.load(json_file) print(data)

输出示例:

{ name : Alice , age : 30, city : New York , skills : [ Python , Machine Learning ]}

5. 自定义 JSON 编码

如果你有自定义的类对象并想要将其转换为 JSON,可以通过实现自定义的编码器:

import jsonclass Employee: def __init__(self, name, age, position): self.name = name self.age = age self.position = position# 自定义的 JSON 编码器def encode_employee(obj): if isinstance(obj, Employee): return {'name': obj.name, 'age': obj.age, 'position': obj.position} raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")# 创建 Employee 对象employee = Employee("John", 28, "Software Engineer")# 使用自定义编码器将对象转换为 JSON 字符串json_str = json.dumps(employee, default=encode_employee)print(json_str)

输出示例:

{ name : John , age : 28, position : Software Engineer }

6. 格式化 JSON 输出

使用 json.dumps() 时,可以通过 indent 参数生成格式化的 JSON 字符串,便于阅读。

import jsondata = { "name": "Alice", "age": 30, "city": "New York", "skills": ["Python", "Machine Learning"]}# 生成格式化的 JSON 字符串json_str = json.dumps(data, indent=4)print(json_str)

输出示例:

{ "name": "Alice", "age": 30, "city": "New York", "skills": [ "Python", "Machine Learning" ]}

7. 处理复杂对象

如果需要序列化更复杂的对象,可以通过自定义 JSONEncoder 类来处理。

import jsonclass Employee: def __init__(self, name, age, position): self.name = name self.age = age self.position = positionclass EmployeeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Employee): return {'name': obj.name, 'age': obj.age, 'position': obj.position} return super().default(obj)employee = Employee("John", 28, "Software Engineer")# 使用自定义的编码器将对象转换为 JSON 字符串json_str = json.dumps(employee, cls=EmployeeEncoder)print(json_str)

输出示例:

{ name : John , age : 28, position : Software Engineer }

JSONL

JSONL(JSON Lines)是一种简单的文件格式,专门用于存储多个JSON对象,每个对象占用一行。JSONL文件的扩展名通常为 .jsonl 或 .ndjson(Newline Delimited JSON)。这种格式在处理大量结构化数据时非常有效,因为它允许逐行读取和处理数据。

下面是JSONL的常见用法示例,包括如何在Python中读取和写入JSONL格式的数据。

1. JSONL 文件的结构

一个JSONL文件可能看起来如下:

{"name": "Alice", "age": 30, "city": "New York"}{"name": "Bob", "age": 25, "city": "Los Angeles"}{"name": "Charlie", "age": 35, "city": "Chicago"}

每一行都是一个有效的JSON对象,行与行之间用换行符 \n 分隔。

2. 读取 JSONL 文件

使用Python读取JSONL文件时,可以逐行处理文件中的JSON对象:

import json# 读取 JSONL 文件with open('data.jsonl', 'r') as jsonl_file: for line in jsonl_file: # 解析每一行的 JSON 对象 data = json.loads(line) print(data)

输出示例:

{'name': 'Alice', 'age': 30, 'city': 'New York'}{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}{'name': 'Charlie', 'age': 35, 'city': 'Chicago'}

3. 写入 JSONL 文件

写入JSONL文件时,可以逐行将多个JSON对象写入文件,每个对象占用一行:

import json# 准备要写入的多个 JSON 对象data_list = [ {"name": "Alice", "age": 30, "city": "New York"}, {"name": "Bob", "age": 25, "city": "Los Angeles"}, {"name": "Charlie", "age": 35, "city": "Chicago"}]# 写入 JSONL 文件with open('data.jsonl', 'w') as jsonl_file: for data in data_list: jsonl_file.write(json.dumps(data) + '\n')

4. 追加写入 JSONL 文件

如果需要追加数据到已有的JSONL文件中,可以使用追加模式 a :

import json# 要追加写入的 JSON 对象new_data = {"name": "Diana", "age": 28, "city": "Houston"}# 追加写入 JSONL 文件with open('data.jsonl', 'a') as jsonl_file: jsonl_file.write(json.dumps(new_data) + '\n')

5. 处理大数据集

由于JSONL格式允许逐行读取和处理数据,特别适合用于处理大数据集。比如当数据量较大时,可以用下面的方式逐行读取并处理,而不需要将整个文件一次性加载到内存中:

import json# 逐行处理大数据集with open('large_data.jsonl', 'r') as jsonl_file: for line in jsonl_file: data = json.loads(line) # 对每一行的数据进行处理 process_data(data)

6. 与Pandas集成

如果你需要将JSONL文件的数据加载到Pandas DataFrame中,Pandas的 read_json 方法也支持读取JSONL格式的数据:

import pandas as pd# 使用 Pandas 读取 JSONL 文件df = pd.read_json('data.jsonl', lines=True)print(df)

输出示例:

name age city
0 Alice 30 New York
1 Bob 25 Los Angeles
2 Charlie 35 Chicago

总结

JSONL格式是一种非常实用的数据存储格式,特别适合处理大型、结构化的数据集。使用它的主要优点包括:

逐行读取:有效处理大文件,节省内存。简便性:每一行都是独立的JSON对象,便于解析和处理。灵活性:可以很容易地将数据追加到已有文件中。

通过上述方法,您可以轻松地在Python中读取、写入和处理JSONL格式的数据。

python json jsonl 的用法详解