1

This is the cred.json file I am trying to parse in my program.

{"accounts":[
        {
                "id":"1",
                "username":"user1",
                "password":"password1"
        },
        {
                "id":"2",
                "username":"user2",
                "password":"password2"
        }
]}

Here is the code I use for it. This works, but I know it isn't the best way to do it.

import json

with open('cred.json') as cred_file:
        parsed_json = json.load(cred_file)
        cred_file.close

        for x in range(0,2):
                user = parsed_json["accounts"][x]["username"]
                password = parsed_json["accounts"][x]["password"]
                print user, ":", password

I want to do the same thing, without specifying the range for the loop. When I try to do the same with iteritems() or get() it is giving me error saying unicode doesn't support those functions.

Please suggest me a better way to do this.

2 Answers 2

3

parsed_json has the entire dict loaded, which contains one key "account" whose value is a list of accounts, as dicts. So instead doing of the range+index lookup, loop over the accounts list directly:

for account in parsed_json["accounts"]:
    user = account["username"]
    password = account["password"]
    print user, ":", password

Also, you don't need cred_file.close (which should be cred_file.close() btw) since it closes after you exit the with context. The correct way would be:

with open('cred.json') as cred_file:
    parsed_json = json.load(cred_file)

for account in parsed_json["accounts"]:
    user = account["username"]
    password = account["password"]
    print user, ":", password
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I missed noticing that 'accounts' was a list.
0

With Python 3

import json
with open('cred.json') as f:
    lines_read = f.readlines()

json_str = ''.join(lines_read)
json_dict = json.loads(json_str)

for account in json_dict['accounts']:
    user = account['username']
    password = account['password']
    print(user, ':', password)

The basic idea is to use python's iterators.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.