詳解python讀寫(xiě)json文件
python處理json文本文件主要是以下四個(gè)函數(shù):
函數(shù) | 作用 |
---|---|
json.dumps | 對(duì)數(shù)據(jù)進(jìn)行編碼,將python中的字典 轉(zhuǎn)換為 字符串 |
json.loads | 對(duì)數(shù)據(jù)進(jìn)行解碼,將 字符串 轉(zhuǎn)換為 python中的字典 |
json.dump | 將dict數(shù)據(jù)寫(xiě)入json文件中 |
json.load | 打開(kāi)json文件,并把字符串轉(zhuǎn)換為python的dict數(shù)據(jù) |
json.dumps / json.loads
數(shù)據(jù)轉(zhuǎn)換對(duì)照:
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
寫(xiě)入json的內(nèi)容只能是dict類型,字符串類型的將會(huì)導(dǎo)致寫(xiě)入格式問(wèn)題:
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ù)類型寫(xiě)入:
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é)
本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
python shell命令行中import多層目錄下的模塊操作
這篇文章主要介紹了python shell命令行中import多層目錄下的模塊操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03一條命令解決mac版本python IDLE不能輸入中文問(wèn)題
本文通過(guò)一條命令幫助大家解決mac版本python IDLE無(wú)法輸入中文問(wèn)題,需要的朋友可以參考下2018-05-05python之基數(shù)排序的實(shí)現(xiàn)
這篇文章主要介紹了python之基數(shù)排序的實(shí)現(xiàn),本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07python中的對(duì)象拷貝示例 python引用傳遞
你想復(fù)制一個(gè)對(duì)象?因?yàn)樵赑ython中,無(wú)論你把對(duì)象做為參數(shù)傳遞,做為函數(shù)返回值,都是引用傳遞的2014-01-01Python中不可錯(cuò)過(guò)的五個(gè)超有用函數(shù)
在本文中,我們用代碼詳細(xì)說(shuō)明了Python中超實(shí)用的5個(gè)函數(shù)的重要作用,這些函數(shù)雖然簡(jiǎn)單,但卻是Python中功能最強(qiáng)大的函數(shù),下面一起來(lái)看看文章的詳細(xì)介紹吧,希望對(duì)你的學(xué)習(xí)有所幫助2022-01-01python+opencv實(shí)現(xiàn)目標(biāo)跟蹤過(guò)程
這篇文章主要介紹了python+opencv實(shí)現(xiàn)目標(biāo)跟蹤過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06