最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解python讀寫json文件

 更新時(shí)間:2021年12月16日 16:07:13   作者:liulanba  
這篇文章主要為大家介紹了python讀寫json文件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

python處理json文本文件主要是以下四個(gè)函數(shù):

函數(shù) 作用
json.dumps 對數(shù)據(jù)進(jìn)行編碼,將python中的字典 轉(zhuǎn)換為 字符串
json.loads 對數(shù)據(jù)進(jìn)行解碼,將 字符串 轉(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類型,字符串類型的將會導(dǎo)致寫入格式問題:

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)文章

最新評論

昭平县| 甘南县| 新绛县| 汕尾市| 瑞安市| 西平县| 浦县| 鹤庆县| 本溪市| 凤山市| 马龙县| 台南县| 肇庆市| 抚顺县| 社会| 吉木萨尔县| 平乐县| 德江县| 射洪县| 乐安县| 彭州市| 通化县| 班玛县| 丹阳市| 无锡市| 吉安县| 大邑县| 扬中市| 临沧市| 沾益县| 惠水县| 苍南县| 潜江市| 陇南市| 车致| 项城市| 游戏| 柳林县| 商河县| 隆尧县| 丹阳市|