1. 程式人生 > 其它 >python之json處理

python之json處理

json是一種所有語言都通用的Key-Value資料結構的資料型別,很像Python中的字典,在Python中可以通過json模組對json串和字典進行轉換。

1、把字典轉換成json串

 1 import json
 2 dic = {'zll':{
 3             'addr':'北京','age':28},
 4        'ljj':{
 5             'addr':'北京','age':38}
 6       }
 7 res = json.dumps(dic,ensure_ascii=False,indent=5)  # 把字典轉成json串
 8 # ensure_ascii=False 中文顯示為中文,不加的話中文顯示為encode編碼
 9 # indent=5 縮排5格
10 print(res)

 2、把字典轉換成json並寫入檔案(json.dumps)

 1 import json
 2 dic = {
 3       'zll':{
 4           'addr':'北京',
 5           'age':28
 6       },
 7       'ljj':{
 8           'addr':'北京',
 9           'age':38
10       }
11 }
12 fw = open('user_info.json','w',encoding='utf-8') # 開啟一個檔案
13 dic_json = json.dumps(dic,ensure_ascii=False,indent=5) # 字典轉成json
14 fw.write(dic_json) # 寫入檔案

3、json.dump自動寫入檔案

 1 import json
 2 dic = {
 3       'zll':{
 4           'addr':'北京',
 5           'age':28
 6       },
 7       'ljj':{
 8           'addr':'北京',
 9           'age':38
10       }
11 }
12 fw = open('user_info.json','w',encoding='utf-8') # 開啟一個檔案
13 dic_json = json.dump(dic,fw,ensure_ascii=False,indent=4) # 字典轉成json,直接操作檔案,不用寫入操作

4、使用json.loads將檔案中的json串轉換成字典

1 import json
2 f = open('user_info.json',encoding='utf-8')
3 res = f.read()  # 使用json.loads需要先讀檔案
4 product_dic = json.loads(res)  # 把json串轉換成字典
5 print(product_dic)

5、使用json.load不用先讀檔案,直接使用就可以

1 import json
2 f = open('user_info.json',encoding='utf-8')
3 product_dic = json.load(f)  # 傳一個檔案物件,它會幫你讀檔案
4 print(product_dic)

6、讀取/寫入檔案內容函式

1 import json
2 def op_data(filename,dic=None):
3     if dic:  # dic不為空時,寫入檔案
4         with open(filename,'w',encoding='utf-8') as fw:
5             json.dump(dic,fw,ensure_ascii=False,indent=4)
6     else:    # dic為空時,讀取檔案內容
7         with open(filename, 'r', encoding='utf-8') as fr:
8             return json.load(fr)