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

詳解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'>

總結

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!

相關文章

最新評論

昌宁县| 米林县| 浦城县| 平阳县| 资兴市| 福建省| 三门县| 巴楚县| 县级市| 县级市| 阿尔山市| 建昌县| 独山县| 鹿邑县| 枣强县| 洪湖市| 兴海县| 通州区| 宜兰市| 英吉沙县| 搜索| 磐安县| 灵璧县| 长乐市| 额济纳旗| 外汇| 江华| 永川市| 华蓥市| 建阳市| 长春市| 江口县| 建宁县| 丁青县| 汶上县| 北碚区| 新密市| 漳平市| 中江县| 岫岩| 上杭县|