BigO
BigO

Reputation: 364

Parsing data in a JSON file

I am wanting to parse some information from a JSON file. I cant find a find to successfully retrieve the data I want.

In a file I want to output the profile name.

This is the code on how I am reading and parsing.

with open(json_data) as f:
        accounts = dict(json.loads(f.read()))
        shell_script = accounts['OCredit']['Profile Name']
        print(shell_script)

This gives me the output of

OCredit

In a sense this is what I want, but in the application the value thats now "OCredit"(first bracket) would depend on the user.

with open(json_data) as f:
        accounts = dict(json.loads(f.read()))
        shell_script = accounts['OCredit']
        print(shell_script)

This outputs :

{'Profile Name': 'OCredit', 'Name': 'Andrew Long', 'Email': 
'[email protected]', 'Tel': '2134568790', 'Address': '213 clover ','Zip': 
'95305', 'City': 'brooklyn', 'State': 'NY','CreditCard':'213456759090', 
'EXP': '12/21', 'CVV': '213'}

The actual JSON file is :

{'OCredit': {'Profile Name': 'OCredit',
 'Name': 'Andrew Long',
 'Email': '[email protected]',
 'Tel': '2134568790',
 'Address': '213 clover ',
 'Zip': '95305',
 'City': 'Brooklyn',
 'State': 'NY',
 'CreditCard': '213456759090',
 'EXP': '12/21',
 'CVV': '213'}}

So, to sum it up. I want to get inside JSON file and just print out the value that "Profile Name" has without hardcoding the fist value of the bracket.

Im not sure if I have to change the way im saving the JSON file to achieve this. Any help would be appreciated.

Upvotes: 3

Views: 116

Answers (1)

Kevin Fang
Kevin Fang

Reputation: 2012

Try this:

for key in accounts:
    print(accounts[key]['Profile Name'])
    # OCredit

Or:

for value in accounts.values():
    print(value['Profile Name'])

Upvotes: 4

Related Questions