为了账号安全,请及时绑定邮箱和手机立即绑定

使用 python 将项目添加到 json 对象

使用 python 将项目添加到 json 对象

慕尼黑8549860 2023-01-04 16:10:45
我有一个包含用户级别和经验的简单 json 文件,格式如下:{    "users" : {        "1" : [0, 1],        "2" : [10, 2],    }}该users对象使用用户 ID 作为[xp, level]数组值的键。我需要能够将新用户写入该文件,以便以后我可以将其称为data["users"][id].到目前为止,这是我的代码,但它实际上并没有写入文件。import jsondef create_user(id):    with open("test.json") as file:        data = json.load(file)        temp = data["users"]  # get the users object.        temp[str(id)] = [0, 0]        # [0, 0] would be the default, until the user        # gains levels and xp.    print('user added to file.')我该怎么做才能将用户添加到users对象并保存到文件中?谢谢。
查看完整描述

1 回答

?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

something = {

    "users" : {

        "1" : [0, 1],

        "2" : [10, 2],

    }

}

something["users"]["3"] = [-1,-2]

print(something)

{'users': {'1': [0, 1], '2': [10, 2], '3': [-1, -2]}}

如果你想把它保存为 json


something = json.dumps(something)

something = json.loads(something)

将所有内容转储到文件中


with open(my_file_loaction, 'w') as json_file:

    json.dump(something, json_file)


查看完整回答
反对 回复 2023-01-04
  • 1 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信