首页 > 解决方案 > 使用 for 循环将数据写入 JSON 文件

问题描述

我当前的 sample.json 看起来像这样

{
    "clients":[
        {
            "username":"user1",
            "level":"100"
        },

        {
            "username":"user2",
            "level":"200"
        }
    ]
}

如何使用 json 库在 Python 中添加第三个用户,使文件最终看起来像这样?

{
    "clients":[
        {
            "username":"user1",
            "level":"100"
        },

        {
            "username":"user2",
            "level":"200"
        },
        
        {
            "username":"user3",
            "level":"300"
        }
    ]
}

使用这种方法会给我 TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

import json

data= {
    "username":"user3",
    "level":"300",
}
    

with open('sample.json') as data_file:
    old_data = json.load(data_file)

data = old_data + data
with open('sample.json', 'w') as outfile:
    json.dump(data, outfile)

标签: pythonjson

解决方案


old_data['clients'].append(data)
with open('sample.json', 'w') as outfile:
    json.dump(old_data, outfile)

当然,old_data使用不同的名称可能会更好,例如json_data,即不暗示“未更新”的名称。


推荐阅读