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) = > <class 'list'>
[
    {
        "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://www.cnblogs.com/hi3254014978/p/15707523.html