python 操作json資料
阿新 • • 發佈:2022-06-01
簡介
JSON(JavaScript Object Notation, JS物件簡譜)是一種輕量級的資料交換格式,通常是以鍵值對的方式呈現,其簡潔和清晰的層次結構使得JSON成為理想的資料交換語言,而在Python中處理JSON格式的模組有json和pickle兩個。
json模組和pickle都提供了四個方法:dumps, dump, loads, load
序列化:將python的資料轉換為json格式的字串
反序列化:將json格式的字串轉換成python的資料型別
dumps與loads
dumps與loads主要是針對於json資料的處理,更加關注於資料型別本身。
json_data = {'test': {'test1_1': 1}, 'test2': {'test2_2': {'test2_3': 2}}, 'test3': {'test3_2': {'test3_3': {'test3_4': 3}}}} content = json.dumps(json_data) print(content) print(type(content)) content = json.loads(content) print(content) print(type(content))
{"test": {"test1_1": 1}, "test2": {"test2_2": {"test2_3": 2}}, "test3": {"test3_2": {"test3_3": {"test3_4": 3}}}}
<class 'str'>
{'test': {'test1_1': 1}, 'test2': {'test2_2': {'test2_3': 2}}, 'test3': {'test3_2': {'test3_3': {'test3_4': 3}}}}
<class 'dict'>
dump與load
dump與load主要是針對於json檔案的處理。
test.json
{
"test":{
"test1_1":1
},
"test2":{
"test2_2":{
"test2_3":2
}
},
"test3":{
"test3_2":{
"test3_3":{
"test3_4":3
}
}
}
}
讀取json資料並寫入新的json資料
import json, os JSON_PATH = os.path.join(os.path.dirname(__file__), 'test.json') JSON_PATH2 = os.path.join(os.path.dirname(__file__), 'test2.json') with open(JSON_PATH, mode='r', encoding='utf8') as r_f: content = json.load(r_f) print(content) print(type(content)) with open(JSON_PATH2, mode='w', encoding='utf-8') as w_f: json.dump(content, w_f, indent=True)
{'test': {'test1_1': 1}, 'test2': {'test2_2': {'test2_3': 2}}, 'test3': {'test3_2': {'test3_3': {'test3_4': 3}}}}
<class 'dict'>
總結
json.dumps、json.dump是將python資料型別轉換為json資料的字串型別。
json.loads、json.load是將json資料的字串型別轉換為python資料型別,一般為字典
json.dumps與json.loads主要是針對於json資料的處理,更加關注於資料型別本身。
json.dump與json.load主要是針對於json檔案的處理。