引言
在這個數字化的時代,數據的重要性隨着人類社會的發展而日益凸顯。而在Python編程語言中,常常需要使用JSON進行數據交互。因此,把Python List轉換成JSON格式數據是一項常見的任務。下面,我們將詳細介紹Python List如何轉換成JSON格式數據。
什麼是JSON數據
JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。它基於JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999,使用文本格式來存儲和交換數據。JSON數據能夠像Python List、Dict一樣表達數據。
Python List轉換成JSON格式數據
方案一:使用Python內置模塊 json.dumps()
Python內置模塊json提供了json.dumps()方法,可以把Python object轉換成JSON格式數據。其中,dumps是“dump string”的縮寫,意思是把對象轉成一個JSON格式的字符串。
import json myList = [1,2,3,4,5] json_str = json.dumps(myList) print("JSON格式數據: ") print(json_str)
輸出結果:
JSON格式數據: [1, 2, 3, 4, 5]
方案二:使用Python內置模塊 json.dump()
Python內置模塊json提供了json.dump()方法,與json.dumps()的區別在於,json.dump()將Python Object轉換成JSON Format的形式輸出到文件中。
import json myList = [1,2,3,4,5] with open('output.json', 'w') as f: json.dump(myList, f) # 輸出結果:output.json文件中的內容為 [1,2,3,4,5]
方案三:使用Python內置模塊 json.JSONEncoder
Python內置模塊json提供了json.JSONEncoder類,使用該類可以定製Python object到json字符串的轉換過程。
import json class MyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, set): return list(obj) return json.JSONEncoder.default(self, obj) myList = [1,2,3,4,5, set([6,7,8])] json_str = json.dumps(myList, cls=MyEncoder) print(json_str)
輸出結果:
[1,2,3,4,5,[6,7,8]]
總結
通過上述三種方法,我們可以很方便地把Python List轉換成JSON格式數據。其中,json.dump()和json.JSONEncoder類更適合於把Python Object轉換成JSON Format,並且處理的時候也更加靈活。
希望本文對您重視數據交互的Python程序員有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/295211.html