python 读写json文件

python 读写json文件,第1张

python 读写json文件

我们都知道json.loads() 和 json.dumps() 分别用来将字符串装换成 json 和 将 json 转换成字符串,那读取 json 文件怎么 *** 作呢,下面我们来看一下:

结论

使用 json.load 来读取 json 文件内容,json.dump()来格式化内容到json文件

读取 json 文件
    with open("test.json", "r") as json_file:
        json_dict = json.load(json_file)
        print(json_dict)
        print("type(json_dict) = >", type(json_dict))
        print(json.dumps(json_dict, indent=4))
输出结果:
[{'name': 'zhangsan', 'age': 23}, {'name': 'lisi', 'age': 24}]
type(json_dict) = > 
[
    {
        "name": "zhangsan",
        "age": 23
    },
    {
        "name": "lisi",
        "age": 24
    }
]
写入 json 文件
    dict = [
        {
            "name": "zhangsan",
            "age": 23
        },
        {
            "name": "lisi",
            "age": 24
        }
    ]
    with open("test.json", "w") as json_file:
        json_dict = json.dump(dict, json_file)
运行结果

test.json文件多了此次写入的内容

参考:python读写json文件

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5680214.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存