Python – parsing and updating json

Question:

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!

Asked By: R2Bleep2

||

Answers:

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')
Answered By: Vlad

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']}")
Answered By: dev_998

I would 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()
Answered By: rv.kvetch
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.