Python的json讀寫方式和字典與json的相互轉化


在Python中,json指的是符合json語法格式的字符串,可以單行或者多行。

它可以方便的在使用在多種語言中,這里介紹的是在python中的字典(dict)與json字符串相互轉化的方式。

1. 導入json包

import json

2. 初始化一個字典數據

dict_ = {
    'name': 'Jack', 
    'age': 22, 
    'skills': ['Python', 'Java', 'C++', 'Matlab'], 
    'major': '計算機技術',
    'english': '英語六級',
    'school': 'WIT'
}

3. json.dumps(字典):將字典轉為JSON字符串

# 1. json.dumps(字典):將字典轉為JSON字符串,indent為多行縮進空格數,
# sort_keys為是否按鍵排序,ensure_ascii=False為不確保ascii,及不將中文等特殊字符轉為\uXXX等
json_dict = json.dumps(dict_)
print(json_dict)

 

很明顯中文字符被轉化了,於是使用:ensure_ascii=False

# 行縮進和鍵值排序
json_dict_2 = json.dumps(dict_, indent=2, sort_keys=True, ensure_ascii=False)
print(json_dict_2)

3. json.loads(json串),將json字符串轉化成字典

dict_from_str = json.loads(json_dict)
print(dict_from_str)

dict_from_str_2 = json.loads(json_dict_2)
print(dict_from_str_2)

4. json.dump,把字典轉換成json字符串並存儲在文件中,結果文件如下圖:

with open("write_json.json", "w", encoding='utf-8') as f:
    # json.dump(dict_, f)  # 寫為一行
    json.dump(dict_, f, indent=2, sort_keys=True, ensure_ascii=False)  # 寫為多行

5. json.load,從文件打開json數據轉換成字典

with open("write_json.json", encoding="utf-8") as f:
    json_file = json.load(f)
print(json_file)

 

##

參考:

https://www.cnblogs.com/superhin/p/11502830.html

https://www.cnblogs.com/momoyan/p/9145478.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM