0

I've been experimenting with python for a while and just ran into an issue I can't find an answer to. Just started building a small 'banking' console app and it's "database" is in JSON file. Now I added a command called 'transfer' which should transfer 'funds' from one user_id to another. JSON file looks like this:

{
"users": [
    {
        "user_id": "u111111111",
        "pin": "2222",
        "balance": "50800"
    },
    {
        "user_id": "u123456789",
        "pin": "1234",
        "balance": "0"
    }
]
}

Last thing I tried was something like this and got completely stuck.

user_database = 'accounts.json'
    ujf = json.loads(open(user_database, 'r+').read())

    for element in ujf['users']:
        if (element['user_id'] == str(user_id_one)):
            element['balance'] = str(user_one_new_balance)
        else:
            pass

How do I update the 'balance' value for user_id u111111111 and for user_id u123456789 and save the file, without creating a new file?

3
  • 1
    Having a JSON for a database is a poor idea. By the way you have to handle a ledger and compute the balance from this ledger based on initial values. Commented Dec 16, 2020 at 9:41
  • 1
    Does this answer your question? Save Python dictionary to file, and update it periodically Commented Dec 16, 2020 at 9:43
  • It looks like you already solved your problem. Now you just need to dump the dict back to a JSON file. Have you looked up how to do that? Commented Dec 16, 2020 at 9:44

1 Answer 1

1

First import JSON module:

import json

Then load the JSON file as dictionary:

d = json.load(r'PATH')

Then inside the loop you can assign user['balance'] to whatever you like, e.g. 8 here:

for user in d['users']:
     if user['user_id'] in ['u111111111','u123456789']:
         user['balance'] = 8

Then dump back:

json.dump(d,(open(r'PATH','w')))
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.