Python - 用python修改json对象

时间:2018-05-15 03:10:18

标签: python json

with open("attacks.json") as json_data:
    items = json.load(json_data)

if int(data["balance"]) => 0:
    total = int(data["balance"]) - int(quantity) * int(items[weapon]["purchase_cost"])
    total = int(total)

    profileData[ctx.message.author.id]["balance"] = "{}".format(total)

    with open("{}.json".format(ctx.message.author.id), "w") as json_file:
        json.dump(data, json_file)

所以基本上我希望这个工作。

profile_template = {
  ctx.message.author.id: {
    "name": ctx.message.author.name,
    "id": ctx.message.author.id,
    "balance": "1000",
    "shield_hitpoints": "2500",
    "defense_power": "50",
    "attack_upgrade": "100%",
    "healthpoints_upgrade": "100%",
    "soldier#": "0",
    "sniper#": "0",
    "demolitionist#": "0",
    "armored_vehicle#": "0",
    "tank#": "0",
    "spy#": "0"
  }
}

但是当我修改json文件时,ctx.message.author.id被删除了。如何在修改文件时保留它?

1 个答案:

答案 0 :(得分:0)

好吧,当您打开文件attacks.json时,将其保存到变量items。 然后修改变量profileData。 然后您将变量data写入文件。

这是您错误的来源吗?

您也进行了比较int(data["balance"]) => 0,我认为您的意思是int(data["balance"]) >= 0