Reputation: 42
i have a file like this:
{"user1": {"Login": "Bob", "Secret": "passkey1"}}
{"user2": {"Login": "John", "Secret": "passkey2"}}
with open('users') as data_file:
data = [json.loads(line) for line in data_file]
How i can iterate on user1,2 etc to get they 'Secret'? Users just an example
Upvotes: 0
Views: 74
Reputation: 917
You can try using the following:
import json
{"user1": {"Login": "Bob", "Secret": "passkey1"}}
{"user2": {"Login": "John", "Secret": "passkey2"}}
with open('users.txt') as data_file:
data = [json.loads(line) for line in data_file]
for line in data:
print(line.get(list(line.keys())[0]).get("Secret"))
This will work as long as the format of the dictionary is consistent, but what I mean you have one user per dictionary.
Upvotes: 1
Reputation: 4472
You can try
with open('users') as data_file:
for line in data_file:
for k, v in json.loads(line).items():
print(v['Secret'])
Output
passkey1
passkey2
This code will create for each line a dictionary and then you can extract the 'Secret' value from each one.
Upvotes: 1
Reputation: 3856
with open('users.txt') as data_file:
data = [list(json.loads(line).values())[0]['Secret'] for line in data_file]
print(data)
['passkey1', 'passkey2']
This is what my file looked like
{"user1": {"Login": "Bob", "Secret": "passkey1"}}
{"user2": {"Login": "John", "Secret": "passkey2"}}
Upvotes: 1