詳解python讀寫json文件
python處理json文本文件主要是以下四個函數(shù):
| 函數(shù) | 作用 |
|---|---|
| json.dumps | 對數(shù)據(jù)進行編碼,將python中的字典 轉(zhuǎn)換為 字符串 |
| json.loads | 對數(shù)據(jù)進行解碼,將 字符串 轉(zhuǎn)換為 python中的字典 |
| json.dump | 將dict數(shù)據(jù)寫入json文件中 |
| json.load | 打開json文件,并把字符串轉(zhuǎn)換為python的dict數(shù)據(jù) |
json.dumps / json.loads
數(shù)據(jù)轉(zhuǎn)換對照:
| 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的內(nèi)容只能是dict類型,字符串類型的將會導致寫入格式問題:
with open("res.json", 'w', encoding='utf-8') as fw:
json.dump(json_str, fw, indent=4, ensure_ascii=False)
則json文件內(nèi)容為:
"{\"name\": \"Tom\", \"age\": 18, \"score\": {\"math\": 98, \"chinese\": 99}}"
我們換一種數(shù)據(jù)類型寫入:
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中讀取到的數(shù)據(jù)也是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'>
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
python shell命令行中import多層目錄下的模塊操作
這篇文章主要介紹了python shell命令行中import多層目錄下的模塊操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
一條命令解決mac版本python IDLE不能輸入中文問題
本文通過一條命令幫助大家解決mac版本python IDLE無法輸入中文問題,需要的朋友可以參考下2018-05-05

