1. 程式人生 > >python讀寫json檔案

python讀寫json檔案

JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式。它基於ECMAScript的一個子集。 JSON採用完全獨立於語言的文字格式,但是也使用了類似於C語言家族的習慣(包括C、C++、Java、JavaScript、Perl、Python等)。這些特性使JSON成為理想的資料交換語言。易於人閱讀和編寫,同時也易於機器解析和生成(一般用於提升網路傳輸速率)。

JSON在python中分別由list和dict組成。

這是用於序列化的兩個模組:

  • json: 用於字串和python資料型別間進行轉換
  • pickle: 用於python特有的型別和python的資料型別間進行轉換

Json模組提供了四個功能:dumps、dump、loads、load

pickle模組提供了四個功能:dumps、dump、loads、load

json dumps把資料型別轉換成字串 dump把資料型別轉換成字串並存儲在檔案中  loads把字串轉換成資料型別  load把檔案開啟從字串轉換成資料型別

json是可以在不同語言之間交換資料的,而pickle只在python之間使用。json只能序列化最基本的資料型別,josn只能把常用的資料型別序列化(列表、字典、列表、字串、數字、),比如日期格式、類物件!josn就不行了。而pickle可以序列化所有的資料型別,包括類,函式都可以序列化。

事例:

dumps:將python中的 字典 轉換為 字串

複製程式碼

1 import json
2 
3 test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
4 print(test_dict)
5 print(type(test_dict))
6 #dumps 將資料轉換成字串
7 json_str = json.dumps(test_dict)
8 print(json_str)
9 print(type(json_str))

複製程式碼

loads: 將 字串 轉換為 字典

1 new_dict = json.loads(json_str)
2 print(new_dict)
3 print(type(new_dict))

dump: 將資料寫入json檔案中

1 with open("../config/record.json","w") as f:
2     json.dump(new_dict,f)
3     print("載入入檔案完成...")

load:把檔案開啟,並把字串變換為資料型別

複製程式碼

1 with open("../config/record.json",'r') as load_f:
2     load_dict = json.load(load_f)
3     print(load_dict)
4 load_dict['smallberg'] = [8200,{1:[['Python',81],['shirt',300]]}]
5 print(load_dict)
6 
7 with open("../config/record.json","w") as dump_f:
8     json.dump(load_dict,dump_f)

複製程式碼