「python」Json模塊dumps、loads、dump、load函數介紹

1、json.dumps()

json.dumps()用於將dict類型的數據轉成str,因為如果直接將dict類型的數據寫入json文件中會發生報錯,因此在將數據寫入時需要用到該函數。

import json

jsontest = {'h':1,'e':2,'l':3,'l':4,'o':5}

jsonObj = json.dumps(jsontest)

print(jsontest)

print(jsonObj)

print(type(jsontest))

print(type(jsonObj))

查看輸出結果:

{'h': 1, 'e': 2, 'l': 4, 'o': 5}

{"h": 1, "e": 2, "l": 4, "o": 5}

2、json.loads()

json.loads()用於將str類型的數據轉成dict。

import json

jsontest = { 'h':1,'e':2,'l':3,'l':4,'o':5 }

jsonDumps = json.dumps(jsontest)

jsonLoads = json.loads(jsonDumps)

print(jsontest)

print(jsonDumps)

print(jsonLoads)

print(type(jsontest))

print(type(jsonDumps))

print(type(jsonLoads))

輸出結果:

{'h': 1, 'e': 2, 'l': 4, 'o': 5}

{"h": 1, "e": 2, "l": 4, "o": 5}

{'h': 1, 'e': 2, 'l': 4, 'o': 5}

3、json.dump()

json.dump()用於將dict類型的數據轉成str,並寫入到json文件中。下面兩種方法都可以將數據寫入json文件

import json

jsontest = { 'h':1,'e':2,'l':3,'l':4,'o':5 }

json_filename = r'C:/Users/Leowen/Desktop/jsontest.json'

# solution 1

jsObj = json.dumps(jsontest)

with open(json_filename, "w") as f:

f.write(jsObj)

f.close()

# solution 2

json.dump(jsontest,open(json_filename,"w"))

輸出結果為:

「python」Json模塊dumps、loads、dump、load函數介紹

4、json.load()

json.load()用於從json文件中讀取數據。

import json

json_filename = r'C:/Users/Leowen/Desktop/jsontest.json'

jsonObj = json.load(open(json_filename))

print(jsonObj)

print(type(jsonObj))

for key in jsonObj.keys():

print("key : {} value : {}".format(key,jsonObj.get(key)))

輸出結果:

{'h': 1, 'e': 2, 'l': 4, 'o': 5}

key : h value : 1

key : e value : 2

key : l value : 4

key : o value : 5

參考:https://blog.csdn.net/mr_evanchen/article/details/77879967

最後的話,最近搭建了一個博客網站,會分享python,機器視覺等文章,歡迎訪問:

https://0leo0.github.io

「python」Json模塊dumps、loads、dump、load函數介紹


分享到:


相關文章: