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

Time:05-25

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:

{
    "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...

CodePudding user response:

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.

  • Related