python-dict检查json-keys值是否为空



在传递它们之前,我想检查配置文件中与json键对应的值是否为空。我该怎么做这个

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

最新更新