0

I have a simple json file containing user levels and experience, in this format:

{
    "users" : {
        "1" : [0, 1],
        "2" : [10, 2],
    }
}

The users object uses the user id as keys for the [xp, level] array values. I need to be able to write a new user to the file, such that later I can call it as data["users"][id].

Here's my code so far, but it doesn't actually write to the file.

import json

def 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.')

What can I do to make it add the user to the users object and save to the file? Thanks.

1 Answer 1

2
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]}}

if you want to keep it as json

something = json.dumps(something)
something = json.loads(something)

to dump everything to a file

with open(my_file_loaction, 'w') as json_file:
    json.dump(something, json_file)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.