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 (ie) 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.
PS: 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.
found = "hosts" in data
print(found)
Found will return either True or False at this case.
Only one other answer seemed to answer your 1st question. The error is that the key was not found, so it raises KeyError
. While there are multiple ways to fix this, the probably easiest (subjective) to understand is this code snippet:
try:
data = i['hosts']
except KeyError:
#notfound
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.