1. json序列化(字典轉成字符串)方法:json
dumps:無文件操做 dump:序列化+寫入文件spa
2. json反序列化(字符串轉成字典)方法:code
loads:無文件操做 load: 讀文件+反序列化blog
例子:dumps(字典轉換成字符串,再寫入文件)utf-8
d = {'s':'you','d':'are'} import json #字典轉換成字符串再寫入文件 with open('3.json', 'w', encoding='utf-8') as f: s = json.dumps(d, ensure_ascii=False, indent=4)#把字典轉成json,字符串,ensure_ascii=False表示寫入後中文直接寫成中文,indent = 4表示設置縮進 f.write(s)
dumps(字典轉換成字符串,同時寫入文件)ci
d = {'s':'you','d':'are'} import json #字典轉換成字符串再寫入文件 with open('3.json', 'w', encoding='utf-8') as f: # s = json.dumps(d, ensure_ascii=False, indent=4)#把字典轉成json,字符串,ensure_ascii=False表示寫入後中文直接寫成中文,indent = 4表示設置縮進 # f.write(s) json.dump(d, f, indent=4, ensure_ascii=False)#dumps操做字符串,dump操做文件
loads(讀取文件中字典格式字符串,再轉換成字典)
import json #文件中讀取字典格式字符串,再轉換成字典 with open('3.txt', encoding='utf-8') as fr: result = fr.read() print(type(result)) dic = json.loads(result) print(dic, type(dic))
load(直接從文件中讀取字典格式字符串,並轉換成字典)字符串
import json #文件中讀取字典格式字符串,再轉換成字典 with open('3.txt', encoding='utf-8') as fr: # result = fr.read() # print(type(result)) # dic = json.loads(result) # print(dic, type(dic)) result = json.load(fr)#load 字典格式字符串直接轉換成字典 print(type(result))