Pulldown
Pulldown

Reputation: 57

Attempting to add an element to existing JSON with python

I am making a discord bot that uses an experience and money system. I have an existing users.json which looks like this (changed ids to random numbers):

{
    "12345678987654321": {
        "experience": 177,
        "level": 5,
        "money": 2250
    },
    "12345678987654321": {
        "experience": 0,
        "level": 1,
        "money": 250
    }
}

I want to add an additional field to look like this:

{
    "12345678987654321": {
        "experience": 177,
        "level": 5,
        "money": 2250,
        "new": 0
    },
    "12345678987654321": {
        "experience": 0,
        "level": 1,
        "money": 250,
        "new": 0
    }
}

What I am currently attempting to do is this:

async def create_user(user):
    users = await get_user_data()
    if str(user.id) not in users:
        users[str(user.id)] = {}
        users[str(user.id)]['experience'] = 0
        users[str(user.id)]['level'] = 1
        users[str(user.id)]['money'] = 250
    else:
        return False

    with open('users.json', 'w') as f:
        json.dump(users, f, sort_keys = True, indent = 4, ensure_ascii = False)
    return True

async def get_user_data():
    with open('users.json', 'r') as f:
        users = json.load(f)
    return users

async def new_field(ctx):
    user = ctx.author
    a = await create_user(user)
    users = await get_user_data()
    if not users[str(user.id)]['new']:
        users[str(user.id)]['new'] = 0
        return True
    else:
        return False
    with open('users.json', 'w') as f:
        json.dump(users, f, sort_keys = True, indent = 4, ensure_ascii = False)

Upvotes: 1

Views: 73

Answers (1)

uingtea
uingtea

Reputation: 6524

to check object key not exist

if key not in obj:

not

if not obj[key]:

in your code

if 'new' not in users[str(user.id)]:
    users[str(user.id)]['new'] = 0
    return True

Upvotes: 1

Related Questions