Python json 讀取 json 文件並轉為 dict


Python json 讀取 json 文件並轉為 dict

在 D 盤 新建 test.json:

{
    "test": "測試\n換行",
    "dict": {
        "list": [0, "str\""],
        "num": 0
    }
}

json 格式編寫:

json 格式大致以 python 的 dict {} 格式來編寫即可,只是要注意字符串不能用單引號'  ',一定要用雙引號"  "

字符串支持轉義

 1 import sys
 2 import os
 3 import json
 4 
 5 p = r'd:\test.json'
 6 if os.path.exists(p):
 7     if sys.version_info.major > 2:
 8         f = open(p, 'r', encoding = 'utf-8')
 9     else:
10         f = open(p, 'r')
11     dict_data = json.load(f)
12     #or
13     dict_data = json.loads(f.read())
14     print(dict_data)

注意:

json 的 load() 和 loads() 的區別

Python 2 和 3 的 open() 的區別


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM