+ 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
8 Respuestas
+ 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
+ 7
Bogdan Priymak can you post the content of your json file? Maybe the format is wrong
+ 6
What's the error you got? The 'else' statement is useless you can remove it. Otehrwise the code should be working fine.
+ 2
Hi!
what happens if you use:
y = json.loads(f) ----> "loads" and not "load"?
+ 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
+ 1
The error I’m getting is TypeError: argument of type ‘int’ is not iterable
+ 1
json.loads also gives me a TypeError: the JSON object must be str, bytes or bytearray
+ 1
The content of the file is just one number “3”. I guess that’s the problem.