python?json?jsonl?的用法詳解
JSON
JSON(JavaScript Object Notation)是一種輕量級(jí)的數(shù)據(jù)交換格式,廣泛用于在客戶端和服務(wù)器之間傳輸數(shù)據(jù)。以下是 Python 中使用 JSON 的一些常見用法:
1. 將 Python 對(duì)象轉(zhuǎn)換為 JSON 字符串
使用 json.dumps()
函數(shù)將 Python 對(duì)象(如字典、列表等)轉(zhuǎn)換為 JSON 字符串。
import json # Python 字典 data = { "name": "Alice", "age": 30, "city": "New York", "skills": ["Python", "Machine Learning"] } # 轉(zhuǎn)換為 JSON 字符串 json_str = json.dumps(data) print(json_str)
輸出示例:
{"name": "Alice", "age": 30, "city": "New York", "skills": ["Python", "Machine Learning"]}
2. 將 JSON 字符串解析為 Python 對(duì)象
使用 json.loads()
函數(shù)將 JSON 字符串解析為 Python 對(duì)象(如字典、列表等)。
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 對(duì)象寫入 JSON 文件
使用 json.dump()
函數(shù)將 Python 對(duì)象寫入到 JSON 文件中。
import json data = { "name": "Alice", "age": 30, "city": "New York", "skills": ["Python", "Machine Learning"] } # 將 Python 對(duì)象寫入 JSON 文件 with open('data.json', 'w') as json_file: json.dump(data, json_file)
4. 從 JSON 文件讀取數(shù)據(jù)
使用 json.load()
函數(shù)從 JSON 文件中讀取數(shù)據(jù)并解析為 Python 對(duì)象。
import json # 從 JSON 文件讀取數(shù)據(jù) 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 編碼
如果你有自定義的類對(duì)象并想要將其轉(zhuǎn)換為 JSON,可以通過實(shí)現(xiàn)自定義的編碼器:
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") # 創(chuàng)建 Employee 對(duì)象 employee = Employee("John", 28, "Software Engineer") # 使用自定義編碼器將對(duì)象轉(zhuǎn)換為 JSON 字符串 json_str = json.dumps(employee, default=encode_employee) print(json_str)
輸出示例:
{"name": "John", "age": 28, "position": "Software Engineer"}
6. 格式化 JSON 輸出
使用 json.dumps()
時(shí),可以通過 indent
參數(shù)生成格式化的 JSON 字符串,便于閱讀。
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)
輸出示例:
{ "name": "Alice", "age": 30, "city": "New York", "skills": [ "Python", "Machine Learning" ] }
7. 處理復(fù)雜對(duì)象
如果需要序列化更復(fù)雜的對(duì)象,可以通過自定義 JSONEncoder
類來處理。
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") # 使用自定義的編碼器將對(duì)象轉(zhuǎn)換為 JSON 字符串 json_str = json.dumps(employee, cls=EmployeeEncoder) print(json_str)
輸出示例:
{"name": "John", "age": 28, "position": "Software Engineer"}
JSONL
JSONL(JSON Lines)是一種簡(jiǎn)單的文件格式,專門用于存儲(chǔ)多個(gè)JSON對(duì)象,每個(gè)對(duì)象占用一行。JSONL文件的擴(kuò)展名通常為 .jsonl
或 .ndjson
(Newline Delimited JSON)。這種格式在處理大量結(jié)構(gòu)化數(shù)據(jù)時(shí)非常有效,因?yàn)樗试S逐行讀取和處理數(shù)據(jù)。
下面是JSONL的常見用法示例,包括如何在Python中讀取和寫入JSONL格式的數(shù)據(jù)。
1. JSONL 文件的結(jié)構(gòu)
一個(gè)JSONL文件可能看起來如下:
{"name": "Alice", "age": 30, "city": "New York"} {"name": "Bob", "age": 25, "city": "Los Angeles"} {"name": "Charlie", "age": 35, "city": "Chicago"}
每一行都是一個(gè)有效的JSON對(duì)象,行與行之間用換行符 \n
分隔。
2. 讀取 JSONL 文件
使用Python讀取JSONL文件時(shí),可以逐行處理文件中的JSON對(duì)象:
import json # 讀取 JSONL 文件 with open('data.jsonl', 'r') as jsonl_file: for line in jsonl_file: # 解析每一行的 JSON 對(duì)象 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文件時(shí),可以逐行將多個(gè)JSON對(duì)象寫入文件,每個(gè)對(duì)象占用一行:
import json # 準(zhǔn)備要寫入的多個(gè) JSON 對(duì)象 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 文件
如果需要追加數(shù)據(jù)到已有的JSONL文件中,可以使用追加模式 'a'
:
import json # 要追加寫入的 JSON 對(duì)象 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. 處理大數(shù)據(jù)集
由于JSONL格式允許逐行讀取和處理數(shù)據(jù),特別適合用于處理大數(shù)據(jù)集。比如當(dāng)數(shù)據(jù)量較大時(shí),可以用下面的方式逐行讀取并處理,而不需要將整個(gè)文件一次性加載到內(nèi)存中:
import json # 逐行處理大數(shù)據(jù)集 with open('large_data.jsonl', 'r') as jsonl_file: for line in jsonl_file: data = json.loads(line) # 對(duì)每一行的數(shù)據(jù)進(jìn)行處理 process_data(data)
6. 與Pandas集成
如果你需要將JSONL文件的數(shù)據(jù)加載到Pandas DataFrame中,Pandas的 read_json
方法也支持讀取JSONL格式的數(shù)據(jù):
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
總結(jié)
JSONL格式是一種非常實(shí)用的數(shù)據(jù)存儲(chǔ)格式,特別適合處理大型、結(jié)構(gòu)化的數(shù)據(jù)集。使用它的主要優(yōu)點(diǎn)包括:
- 逐行讀?。河行幚泶笪募?,節(jié)省內(nèi)存。
- 簡(jiǎn)便性:每一行都是獨(dú)立的JSON對(duì)象,便于解析和處理。
- 靈活性:可以很容易地將數(shù)據(jù)追加到已有文件中。
通過上述方法,您可以輕松地在Python中讀取、寫入和處理JSONL格式的數(shù)據(jù)。
到此這篇關(guān)于python json jsonl 的用法詳解的文章就介紹到這了,更多相關(guān)python json jsonl 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Djongo模塊在Django中使用MongoDB數(shù)據(jù)庫
Django框架為我們提供了簡(jiǎn)潔方便的ORM模型供我們對(duì)數(shù)據(jù)庫進(jìn)行各種操作,但是這個(gè)“數(shù)據(jù)庫”卻并不包括NoSQL的典型——MongoDB。不少Django初學(xué)者也會(huì)到處詢問,如何才能在Django中使用MongoDB。本文將介紹使用Djongo來在Django中集成MongoDB數(shù)據(jù)庫2021-06-06詳解pycharm的python包opencv(cv2)無代碼提示問題的解決
這篇文章主要介紹了詳解pycharm的python包opencv(cv2)無代碼提示問題的解決,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01python3通過udp實(shí)現(xiàn)組播數(shù)據(jù)的發(fā)送和接收操作
這篇文章主要介紹了python3通過udp實(shí)現(xiàn)組播數(shù)據(jù)的發(fā)送和接收操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python中通過@classmethod 實(shí)現(xiàn)多態(tài)的示例
這篇文章主要介紹了Python中通過@classmethod 實(shí)現(xiàn)多態(tài),python中通常使用對(duì)象創(chuàng)建多態(tài)模式,python還支持類創(chuàng)建多態(tài)模式,下面通過一個(gè)例子展示它如何實(shí)現(xiàn)多態(tài),需要的朋友可以參考下2022-11-11linux環(huán)境下安裝pyramid和新建項(xiàng)目的步驟
這篇文章簡(jiǎn)單介紹了linux環(huán)境下安裝pyramid和新建項(xiàng)目的步驟,大家參考使用2013-11-11python繼承threading.Thread實(shí)現(xiàn)有返回值的子類實(shí)例
這篇文章主要介紹了python繼承threading.Thread實(shí)現(xiàn)有返回值的子類實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05