I've been trying to create a script that checks for if a value exists in a json file but I keep getting a error that I don't understand and its the same no matter how I rewrite. my questions are what is the error and how could I fix it? code snippet:
with open('json_file.json') as f:
data = json.load(f)
for i in data:
if i['hosts'] in data:
print("it found it")
error message:
Ignoring exception in command myprofile:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 64, in myprofile
if i['hosts'] in data:
KeyError: 'hosts'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'hosts'
Try using i.get('hosts', None)
instead of i['hosts']
.
For example if your json file looks like this
{'field1': {'someotherfield': 'xxxx'}, 'field2': {'hosts': 'host1'}}
when the statement for i in data:
runs it loops through field1
& field2
. The statement i['hosts']
requires every field (i.e) field1, field2 in our case to have a key called as hosts
. If some field doesn't have that key it raises KeyError
. Instead use i.get('hosts', None)
it would firstly check for the key named hosts
, if it is not present it simply returns None.
P.S : If you are working with a simple dictionary, then @JaniniRami's solution should work fine for you, if you are working with a nested dictionary or json like dictionary then my solution would do it for you.