0

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

3 Answers3

1
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"}}
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
1

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.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17
  • Thank you, this example is the best way for me – Explorethetruth Jun 16 '20 at 10:34
  • You welcome, Happy to help. It will be appreciated if you can mark the answer. – Leo Arad Jun 16 '20 at 10:36
  • Can you explain one more thing? When i trying to iterate over the all passkeys i need to stop iterations when some condition is true. if v['Secret'] == variable: print OK else: BAD But it prints one OK and one BAD in depend of passkey count – Explorethetruth Jun 16 '20 at 12:20
  • do an if statement like `if v['Secret'] == 'passkey1':` and then you can use `break` to exit the loop. – Leo Arad Jun 16 '20 at 12:22
  • `if v['Secret'] == Token: Name = (v['Login']) print(Name) bot.reply_to(message, 'Alloha, ' + Name) break else: bot.reply_to(message, "I can't identify you') ` I receive both answers :( – Explorethetruth Jun 16 '20 at 12:26
  • Yes, That is because it's a nested loop in order to make it work you need also to break the outer loop this link may help you with that https://stackoverflow.com/questions/653509/breaking-out-of-nested-loops – Leo Arad Jun 16 '20 at 12:34
  • Oh, really. Thanks a lot. :) – Explorethetruth Jun 16 '20 at 12:40
1

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.

Mateo Lara
  • 827
  • 2
  • 12
  • 29