+ 1

An error when trying to run “if” block with contents of json file

Is there a different way to check if there’s specific data in json format? with open(file, ‘r’) as f: x = ‘example’ y = json.load(f) if x in y: print(‘doesnt work’) else: pass

4th Jul 2020, 5:46 PM
Bohdan Priymak
Bohdan Priymak - avatar
8 Antworten
+ 7
Yes, json file should look like a python dictionary, the brackets are a must. Example: (let's say this json file holds the name and age of students), it should look like this: { "john": 15, "alex": 17, "sofia": 16, "mark": 17 } Using "if x in y" will only check the names but not the age, meaning: "'john' in y" will return True "17" in y will return False
4th Jul 2020, 6:11 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 7
Bogdan Priymak can you post the content of your json file? Maybe the format is wrong
4th Jul 2020, 6:02 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 6
What's the error you got? The 'else' statement is useless you can remove it. Otehrwise the code should be working fine.
4th Jul 2020, 5:57 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
Hi! what happens if you use: y = json.loads(f) ----> "loads" and not "load"?
4th Jul 2020, 5:59 PM
yyy
+ 2
Thank you, now I get it. The thing is that I was able to use json.write to add just a number 3, so I thought that I should be able to access the file later
4th Jul 2020, 6:32 PM
Bohdan Priymak
Bohdan Priymak - avatar
+ 1
The error I’m getting is TypeError: argument of type ‘int’ is not iterable
4th Jul 2020, 6:01 PM
Bohdan Priymak
Bohdan Priymak - avatar
+ 1
json.loads also gives me a TypeError: the JSON object must be str, bytes or bytearray
4th Jul 2020, 6:02 PM
Bohdan Priymak
Bohdan Priymak - avatar
+ 1
The content of the file is just one number “3”. I guess that’s the problem.
4th Jul 2020, 6:07 PM
Bohdan Priymak
Bohdan Priymak - avatar