Home > database >  Python - parsing and updating json
Python - parsing and updating json

Time:08-25

I'm able to load and parse a json file with Python by referring to list items by name. My users.json data file:

{
    "joe": {
        "secret": "abc123.321def"
    },
    "sarah": {
        "secret": "led789.321plo"
    },
    "dave": {
        "secret": "ghi532.765dlmn"
    }
}

My code - to output the 'secret' value associated with a specific user (e.g. Dave):

import json

with open('users_sample.json') as f:
  users = json.load(f)
  # f.close()

print(users['dave']['secret'])

This outputs Dave's secret:

ghi532.765dlmn

That's easy enough when I can predict or know the user names, but how do I iterate through each user in the users.json file and output each user's 'secret' value?

Thanks in advance!

CodePudding user response:

I want encapsulate the logic to print each user and their associated function into a helper function:

def print_users(users_dict: dict, header='Before'):
    print(f'-- {header}')
    for u in users_dict:
        print(f'  {u}: {users_dict[u].get("secret", "<empty>")}')

Then, upon loading the users object initially via json.load, you can then call the function like so:

print_users(users)

To replace the secret for each user, in this case to replace every occurrence of a dot . with a plus , a simple approach could be to use a for loop to update the users object in place:

for name, user in users.items():
    if 'secret' in user:
        user['secret'] = user['secret'].replace('.', ' ')

Then print the result after the replacements are carried out:

print_users(users, 'After')

Finally, we can write the result users object back out to a file:

with open('users_sample_UPDATED.json', 'w') as out_file:
    json.dump(users, out_file)

The output of the above code, in this case would be:

-- Before
  joe: abc123.321def
  sarah: led789.321plo
  dave: ghi532.765dlmn
-- After
  joe: abc123 321def
  sarah: led789 321plo
  dave: ghi532 765dlmn

The full code:

import json


def main():
    with open('users_sample.json') as f:
        users = json.load(f)

    print_users(users)

    new_users = {name: {'secret': user['secret'].replace('.', ' ')}
                 for name, user in users.items()}

    print_users(new_users, 'After')

    with open('users_sample_UPDATED.json', 'w') as out_file:
        json.dump(new_users, out_file)


def print_users(users_dict: dict, header='Before'):
    print(f'-- {header}')
    for u in users_dict:
        print(f'  {u}: {users_dict[u].get("secret", "<empty>")}')


if __name__ == '__main__':
    main()

CodePudding user response:

Iterate the dictionary using a for loop

code that works:

import json

with open('users_sample.json') as f:
  users = json.load(f)

for user in users:
    print(f"user name: {user} secret: {users[user]['secret']}")

CodePudding user response:

You have a nested dictionary - i.e., each value associated with a top-level key is also a dictionary. You can iterate over those dictionaries with the built-in values() function. This leads to:

print(*[e.get('secret') for e in users.values()], sep='\n')
  • Related