python中json操作


1、寫操作.json文件dumps()、dump()函數

 1 d = {
 2     'zll': {
 3         'addr': '北京',
 4         'age': 28
 5     },
 6     'ljj': {
 7         'addr': '北京',
 8         'age': 38
 9     }
10 }
1 fw = open('user_info.json', 'w', encoding='utf-8')
2 # ensure_ascii:默認值True,如果dict內含有non-ASCII的字符,則會類似\uXXXX的顯示數據,設置成False后,就能正常顯示
3 # dic_json = json.dumps(d,ensure_ascii=False,indent=4)  #字典轉成json格式,字典轉成字符串
4 dic_json = json.dumps(d, ensure_ascii=True, indent=4)  # 字典轉成json格式,字典轉成字符串
5 fw.write(dic_json)
6 fw.close()
結果
 1 {
 2     "zll": { 3 "addr": "\u5317\u4eac", 4 "age": 28 5  }, 6 "ljj": { 7 "addr": "\u5317\u4eac", 8 "age": 38 9  } 10 }

 1 fw = open('user_info.json', 'w', encoding='utf-8')
 2 # ensure_ascii:默認值True,如果dict內含有non-ASCII的字符,則會類似\uXXXX的顯示數據,設置成False后,就能正常顯示
 3 dic_json = json.dumps(d,ensure_ascii=False,indent=4)  #字典轉成json,字典轉成字符串
 5 fw.write(dic_json)
 6 fw.close()

7 結果
{  9 "zll": { 10 "addr": "北京", 11 "age": 28 12  }, 13 "ljj": { 14 "addr": "北京", 15 "age": 38 16  } 17 }

dump() 操作json文件 寫的操作

 1 fw = open('user_info.json', 'w', encoding='utf-8')
 2 json.dump(d,fw,ensure_ascii=False,indent=4)  #操作文件
 3 fw.close()
 4 
 5 結果
 6 {
 7     "zll": {
 8         "addr": "北京",
 9         "age": 28
10     },
11     "ljj": {
12         "addr": "北京",
13         "age": 38
14     }
15 }

2、讀操作load()、loads()

 1 # json串是一個字符串
 2 f = open('product.json',encoding='utf-8')
 3 res = f.read()
 4 product_dic = json.loads(res)  #把json串,變成python的數據類型,只能轉換json串內容
 5 print(product_dic)
 6 print(product_dic['iphone'])
 7 # t = json.load(f)
 8 # print(t) #傳一個文件對象,它會幫你直接讀json文件,並轉換成python數據
 9 # print(t['iphone'])
10 f.close()
11 
12 結果
13 {'iphone': {'color': 'red', 'num': 1, 'price': 98.5}, 'wather': {'num': 100, 'price': 1, 'color': 'white'}}
14 {'color': 'red', 'num': 1, 'price': 98.5}

 

 1 # 文件讀寫
 2 def op_file(file, dict_temp=None):
 3     if dict_temp:
 4         with open(file, 'w', encoding='utf-8') as fw:
 5             json.dump(dict_temp, fw, ensure_ascii=False, indent=4)
 6         return 1
 7     else:
 8         with open(file, 'r', encoding='utf-8') as fr:
 9             dict_temp = json.load(fr)
10         return dict_temp

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM