I have a discord bot saves the users info in a json file like this: https://imgur.com/hM399Pw
So I need to add a new json key (name="House", value=False) to all users.
I tried before json.dump(house, json_file) bot not works.
Important info: I have these functions:
To open a new json account:
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
house = users[str(user.id)]['House'] = False
with open("main.json", 'w') as f:
f.write(json.dumps(house))
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
users[str(user.id)]["House"] = False
To read json file:
async def get_bank_data():
with open("main.json", "r") as f:
users = json.load(f)
return users
Another info: user value is ctx.author
CodePudding user response:
You could write a 1 time method where you loop over all users in your json to add the new field, something like this:
async def open_account(user):
users = await get_bank_data()
for user in users:
house = user['House'] = False
with open("main.json", 'w') as f:
f.write(json.dumps(house))
If you want to add the field for every user in your Server, you could loop over all members to add to your json like so:
users = await get_bank_data()
async for member in guild.fetch_members():
house = users[str(member.id)]['House'] = False
with open("main.json", 'w') as f:
f.write(json.dumps(house))
CodePudding user response:
Just run this script locally to add the "House" key to every user within the main.json file
with open("main.json", "r") as f:
bank_data = json.load(f)
# scroll through every user
for key in bank_data.keys():
# If there is no "House" key for a user
if bank_data[key].get("House") is None:
# Add the key
bank_data[key]["House"] = False
# Save the json
with open("main.json", 'w') as f:
f.write(json.dumps(bank_data))
Btw get_bank_data dont need to be a async funciton as it doesn't use any ascynchronous functionnalities
