开发者社区> 问答> 正文

如何在Python中的json文件中查看元素是否存在?

我想检查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))    

但这似乎不起作用...有帮助吗?

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 20:08:10 1124 0
1 条回答
写回答
取消 提交回答
  • 这是一个简单的解决方案:

    cmd = input().lower()
    if cmd in set(c["commandName"] for c in data["commands"]):
        # do something
    else:
        print(f"Command {cmd} does not exist")
    

    回答来源:stackoverflow

    2020-03-24 20:08:32
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载