1. 程式人生 > >json_Python,函式dumps、loads、dump、load

json_Python,函式dumps、loads、dump、load

轉載記得寫上https://blog.csdn.net/bozhanggu2239/article/details/80832644
"""dumps、loads 、其他、dump、load"""



#  json.dumps()用於將dict型別的資料轉成str,因為如果直接將dict型別的資料寫入json檔案中會發生報錯,因此在將資料寫入時需要用到該函式
"""
import json

first = {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
dumps = json.dumps(first)

print(first) #{'a': '1111', 'c': '3333', 'b': '2222', 'd': '4444'}
print(dumps) #{"a": "1111", "c": "3333", "b": "2222", "d": "4444"} print(type(first)) #<class 'dict'> print(type(dumps)) #<class 'str'> print(type("fw")) #<class 'str'> print(type('sf')) #<class 'str'> Y='_3dumpload.json' #通常使用副檔名為.json來指出檔案儲存的資料為JSON格式
# with open(Y,'w') as f_obj: # f_obj.write(first) #TypeError: write() argument must be str, not dict # with open(Y,'w') as f_obj: f_obj.write(dumps) #{"d": "4444", "a": "1111", "b": "2222", "c": "3333"} #{"d": "4444", "a": "1111", "b": "2222", "c": "3333"}經過dump,得到: #"{\"a\"
: \"1111\", \"b\": \"2222\", \"c\": \"3333\", \"d\": \"4444\"}"\ """ #json.loads()用於將str型別的資料轉成dict。 """ import json first = {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'} dumps = json.dumps(first) dumps_loads = json.loads(dumps) print(first) #{'b': '2222', 'd': '4444', 'a': '1111', 'c': '3333'} print(dumps) #{"d": "4444", "a": "1111", "c": "3333", "b": "2222"} print(dumps_loads) #{'b': '2222', 'd': '4444', 'a': '1111', 'c': '3333'} print(type(first)) #<class 'dict'> print(type(dumps)) #<class 'str'> print(type(dumps_loads)) #<class 'dict'> """ #其他 """ import json first = {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'} dumps = json.dumps(first) #{"d": "4444", "b": "2222", "a": "1111", "c": "3333"}# dumps2 =json.dumps(dumps) #"{\"d\": \"4444\", \"b\": \"2222\", \"a\": \"1111\", \"c\": \"3333\"}" dumps3 =json.dumps(dumps2) #"\"{\\\"d\\\": \\\"4444\\\", \\\"b\\\": \\\"2222\\\", \\\"a\\\": \\\"1111\\\", \\\"c\\\": \\\"3333\\\"}\"" dumps4 =json.dumps(dumps3) #"\"\\\"{\\\\\\\"d\\\\\\\": \\\\\\\"4444\\\\\\\", \\\\\\\"b\\\\\\\": \\\\\\\"2222\\\\\\\", \\\\\\\"a\\\\\\\": \\\\\\\"1111\\\\\\\", \\\\\\\"c\\\\\\\": \\\\\\\"3333\\\\\\\"}\\\"\"" print(dumps) print(dumps2) print(dumps3) #不能把上面的dumps換成dump不然會報錯 print(dumps4)#都是字串的格式<class 'str'> """ #dump和load也是類似dumps和loads的功能,只是必須和檔案操作結合起來,不能單獨出來 # 如json.dump(numbers,f_obj),即編碼的同時將東西寫入檔案 # dumpshe則是不可以。dumps = json.dumps(first) # with open(Y,'w') as f_obj: # f_obj.write(dumps) 這裡分2步走,先編碼後寫入 """ import json #匯入模組json numbers ={'2':3,'5':7,'11':13} Y='_3dumpload.json' #通常使用副檔名為.json來指出檔案儲存的資料為JSON格式 with open(Y,'w') as f_obj: json.dump(numbers,f_obj) #將資料寫進去 {"2": 3, "11": 13, "5": 7} A='_3dumpload.json' with open(A) as f: num=json.load(f) #使用json.load(f)載入儲存在numbers.json'中的資訊 print(num) #{'11': 13, '5': 7, '2': 3} """