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?

ztpoint5
  • 13
  • 2
  • 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. – MetallimaX Dec 16 '20 at 09:41
  • 1
    Does this answer your question? [Save Python dictionary to file, and update it periodically](https://stackoverflow.com/questions/47187250/save-python-dictionary-to-file-and-update-it-periodically) – etch_45 Dec 16 '20 at 09: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? – Iguananaut Dec 16 '20 at 09:44

1 Answers1

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')))
Wasif
  • 14,755
  • 3
  • 14
  • 34