簡體   English   中英

python dict 檢查 json 鍵值是否為空

[英]python dict check if json keys value is empty

我想在傳遞它們之前檢查與我的配置文件中的 json 鍵對應的值是否為空。 我怎么能 go 關於這樣做

def setup_config() -> dict:
    if os.path.isfile("config.json"):
        with open("config.json") as cfg:
            myjson = json.load(cfg)
            if not ('output_directory' and not 'data_directory' and not ('log_directory' in myjson) and not len(
                    myjson['output_directory'])) or len(myjson['data_directory']) or len(myjson['log_directory']) == 0:
                logging.error("Enter directory information in configuration file")
                exit(0)
            cfg_values = {"output_directory": myjson.get("output_directory"),
                          "data_directory": myjson.get("data_directory"),
                          "log_directory": myjson.get("log_directory")}
            json.dumps(cfg_values)
            return cfg_values
    else:
        with open("config.json", "w") as jsonFile:
            cfg_values = {"output_directory": "",
                          "data_directory": "",
                          "log_directory": ""}
            json.dump(cfg_values, jsonFile)
            logging.error("Enter directory information in configuration file")
            exit(1)

在 python 中,如果key不存在, dict.get('key')將返回 None。

foo = {'a': 'hello'}
b = foo.get('b')
if b:
    # b exists, process b
else:
    # handle if b does not exist

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM