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

1
  • 1
    [x[list(x.keys())[0]]["Secret"] for x in data] btw show what you have tried so far next time Commented Jun 16, 2020 at 10:08

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you, this example is the best way for me
You welcome, Happy to help. It will be appreciated if you can mark the answer.
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
do an if statement like if v['Secret'] == 'passkey1': and then you can use break to exit the loop.
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 :(
|
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"}}

Comments

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.

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.