Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中查看json文件中是否存在元素?_Json_Python 3.x - Fatal编程技术网

如何在Python中查看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():

我想检查JSON文件中是否存在命令。 以下是JSON文件:

{
    "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")