JSON 和 Python字典的相互轉換

一、用到的庫:

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文件和程序文件放在同一目錄下

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章