如何在Python中查看json文件中是否存在元素?
我想检查JSON文件中是否存在命令。 以下是JSON文件:如何在Python中查看json文件中是否存在元素?,json,python-3.x,Json,Python 3.x,我想检查JSON文件中是否存在命令。 以下是JSON文件: { "commands":[ { "name":"Help", "commandName":"help", "usage": "help", "function":"print" } ] } 这是我的密码: import random import json def login():
{
"commands":[
{
"name":"Help",
"commandName":"help",
"usage": "help",
"function":"print"
}
]
}
这是我的密码:
import random
import json
def login():
print("Oof")
while True:
Command = input(">")
with open("data.json") as json_file:
data = json.load(json_file)
for p in data['commands']:
if Command in data['commands']:
if Command.lower() == p['commandName']:
eval(p["function"] + '()')
else:
print("Command '{}' does not exist, try 'help'.".format(Command))
但它似乎不起作用。。。有什么帮助吗?这里有一个简单的解决方案:
cmd = input().lower()
if cmd in set(c["commandName"] for c in data["commands"]):
# do something
else:
print(f"Command {cmd} does not exist")