詳解python讀寫json文件
更新時間:2021年12月16日 16:07:13 作者:liulanba
這篇文章主要為大家介紹了python讀寫json文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
python處理json文本文件主要是以下四個函數:
| 函數 | 作用 |
|---|---|
| json.dumps | 對數據進行編碼,將python中的字典 轉換為 字符串 |
| json.loads | 對數據進行解碼,將 字符串 轉換為 python中的字典 |
| json.dump | 將dict數據寫入json文件中 |
| json.load | 打開json文件,并把字符串轉換為python的dict數據 |
json.dumps / json.loads
數據轉換對照:
| json | python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true | True |
| false | False |
| null | None |
代碼示例:
import json
tesdic = {
'name': 'Tom',
'age': 18,
'score':
{
'math': 98,
'chinese': 99
}
}
print(type(tesdic))
json_str = json.dumps(tesdic)
print(json_str)
print(type(json_str))
newdic = json.loads(json_str)
print(newdic)
print(type(newdic))
輸出為:
<class 'dict'>
{"name": "Tom", "age": 18, "score": {"math": 98, "chinese": 99}}
<class 'str'>
{'name': 'Tom', 'age': 18, 'score': {'math': 98, 'chinese': 99}}
<class 'dict'>
json.dump / json.load
寫入json的內容只能是dict類型,字符串類型的將會導致寫入格式問題:
with open("res.json", 'w', encoding='utf-8') as fw:
json.dump(json_str, fw, indent=4, ensure_ascii=False)
則json文件內容為:
"{\"name\": \"Tom\", \"age\": 18, \"score\": {\"math\": 98, \"chinese\": 99}}"
我們換一種數據類型寫入:
with open("res.json", 'w', encoding='utf-8') as fw:
json.dump(tesdic, fw, indent=4, ensure_ascii=False)
則生成的josn就是正確的格式:
{
"name": "Tom",
"age": 18,
"score": {
"math": 98,
"chinese": 99
}
}
同理,從json中讀取到的數據也是dict類型:
with open("res.json", 'r', encoding='utf-8') as fw:
injson = json.load(fw)
print(injson)
print(type(injson))
{'name': 'Tom', 'age': 18, 'score': {'math': 98, 'chinese': 99}}
<class 'dict'>
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
Python 在 VSCode 中使用 IPython Kernel 的方法詳解
這篇文章主要介紹了Python 在 VSCode 中使用 IPython Kernel 的方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
在Python中操作字符串之startswith()方法的使用
這篇文章主要介紹了在Python中操作字符串之startswith()方法的使用,是Python入門學習中的基礎知識,需要的朋友可以參考下2015-05-05
關于Pandas?count()與values_count()的用法及區(qū)別
這篇文章主要介紹了關于Pandas?count()與values_count()的用法及區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05
tensorflow 恢復指定層與不同層指定不同學習率的方法
今天小編就為大家分享一篇tensorflow 恢復指定層與不同層指定不同學習率的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07

