Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – parsing and updating json

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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']}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading