Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to make a functional "if" condition using Json in Python?

I’m trying to do a comparison between a value, if it exists in Json, using "if and else", but it always falls into the "else" condition first.

my code:

with open(arquivo, 'r') as f:
  data= json.load(f)
  data2 = data["Privado"]



baka = 1199736520 #Id exists in json
  for s in data2:
    abc = s["id"]
    if baka == abc:
      print("It's here")
      
    else:
      print("OOPS!")

My Json:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "Privado": [
        {
            "username": "Someone",
            "id": 700829116,
            "date": "21/05/22",
            "time": "15:39:52",
            "link": "https://abc/def"
        },
        {
            "username": "HERE",
            "id": 1199736520,
            "date": "21/05/22",
            "time": "16:37:49",
            "link": "https:/a/somelink"
        },
        {
            "username": "Teacher",
            "id": 5163838307,
            "date": "21/05/22",
            "time": "17:32:09",
            "link": "no link"
        }
    ]
}

Output:

OOPS!
It's here
OOPS!

[Program finished]

If I use "break" in the "else" condition, it doesn’t execute the first condition. So I ask… How to make a condition functional?

If found, print: "I found", if not, print: "I didn’t find" only once…

>Solution :

It seems like you want to check whether the value you are looking for is found at least once.

You can use:

for s in data2:
    if s['id'] == baka:
        print('found')
        break # exit loop
else: # no break
    print('not found')

Note that it’s for/else here, not if/else.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading