JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛用于在客户端和服务器之间传输数据。以下是 Python 中使用 JSON 的一些常见用法:
使用 json.dumps() 函数将 Python 对象(如字典、列表等)转换为 JSON 字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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"]}
使用 json.loads() 函数将 JSON 字符串解析为 Python 对象(如字典、列表等)。
1 2 3 4 5 |
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']}
使用 json.dump() 函数将 Python 对象写入到 JSON 文件中。
1 2 3 4 5 6 7 8 9 10 11 12 |
import json
data = { "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) |
使用 json.load() 函数从 JSON 文件中读取数据并解析为 Python 对象。
1 2 3 4 5 6 |
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']}
如果你有自定义的类对象并想要将其转换为 JSON,可以通过实现自定义的编码器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import json
class 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"}
使用 json.dumps() 时,可以通过 indent 参数生成格式化的 JSON 字符串,便于阅读。
1 2 3 4 5 6 7 8 9 10 11 12 |
import json
data = { "name": "Alice", "age": 30, "city": "New York", "skills": ["Python", "Machine Learning"] }
# 生成格式化的 JSON 字符串 json_str = json.dumps(data, indent=4) print(json_str) |
输出示例:
1 2 3 4 5 6 7 8 9 |
{ "name": "Alice", "age": 30, "city": "New York", "skills": [ "Python", "Machine Learning" ] } |
如果需要序列化更复杂的对象,可以通过自定义 JSONEncoder 类来处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import json
class Employee: def __init__(self, name, age, position): self.name = name self.age = age self.position = position
class 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(JSON Lines)是一种简单的文件格式,专门用于存储多个JSON对象,每个对象占用一行。JSONL文件的扩展名通常为 .jsonl 或 .ndjson(Newline Delimited JSON)。这种格式在处理大量结构化数据时非常有效,因为它允许逐行读取和处理数据。
下面是JSONL的常见用法示例,包括如何在Python中读取和写入JSONL格式的数据。
一个JSONL文件可能看起来如下:
1 2 3 |
{"name": "Alice", "age": 30, "city": "New York"} {"name": "Bob", "age": 25, "city": "Los Angeles"} {"name": "Charlie", "age": 35, "city": "Chicago"} |
每一行都是一个有效的JSON对象,行与行之间用换行符 \n 分隔。
使用Python读取JSONL文件时,可以逐行处理文件中的JSON对象:
1 2 3 4 5 6 7 8 |
import json
# 读取 JSONL 文件 with open('data.jsonl', 'r') as jsonl_file: for line in jsonl_file: # 解析每一行的 JSON 对象 data = json.loads(line) print(data) |
输出示例:
1 2 3 |
{'name': 'Alice', 'age': 30, 'city': 'New York'} {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'} {'name': 'Charlie', 'age': 35, 'city': 'Chicago'} |
写入JSONL文件时,可以逐行将多个JSON对象写入文件,每个对象占用一行:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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') |
如果需要追加数据到已有的JSONL文件中,可以使用追加模式 'a':
1 2 3 4 5 6 7 8 |
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') |
由于JSONL格式允许逐行读取和处理数据,特别适合用于处理大数据集。比如当数据量较大时,可以用下面的方式逐行读取并处理,而不需要将整个文件一次性加载到内存中:
1 2 3 4 5 6 7 8 |
import json
# 逐行处理大数据集 with open('large_data.jsonl', 'r') as jsonl_file: for line in jsonl_file: data = json.loads(line) # 对每一行的数据进行处理 process_data(data) |
如果你需要将JSONL文件的数据加载到Pandas DataFrame中,Pandas的 read_json 方法也支持读取JSONL格式的数据:
1 2 3 4 5 |
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格式是一种非常实用的数据存储格式,特别适合处理大型、结构化的数据集。使用它的主要优点包括:
通过上述方法,您可以轻松地在Python中读取、写入和处理JSONL格式的数据。