一、用到的庫:
json
二、用到的方法:
dumps():將字典轉換爲JSON格式的字符串
loads():將JSON格式的字符串轉化爲字典
dump():將字典轉換爲JSON格式的字符串,並將轉化後的結果寫入文件
load():從文件讀取JSON格式的字符串,並將其轉化爲字典
三、實現代碼
import json
# 原始數據
dict1 = {
'name': '翠花',
'age': 18,
'nickname': 'GreenFlower',
}
print("原始數據類型爲:"+str(type(dict1)))
# 將字典轉換爲JSON格式的字符串
t1 = json.dumps(dict1, ensure_ascii=False)
print("字典轉JSON後數據類型爲:"+str(type(t1)))
print(t1)
# 將JSON格式的字符串轉化爲字典
t2 = json.loads(t1)
print("JSON轉字典後數據類型爲:"+str(type(t2)))
print(t2)
# 將字典轉換爲JSON格式的字符串,並將轉化後的結果寫入文件
filename = 'test1.json'
with open(filename, 'w', encoding='UTF-8') as f:
json.dump(dict1, f, ensure_ascii=False)
# 從文件讀取JSON格式的字符串,並將其轉化爲字典
with open(filename, 'r', encoding='UTF-8') as f:
aa = json.load(f)
print("讀取JSON文件中的內容:")
print(aa)
四、運行結果
五、讀寫的文件附件
test1.json文件和程序文件放在同一目錄下