简体   繁体   中英

Python JSON replace value in specific line

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?

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, eg 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')))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM