【发布时间】:2017-12-31 23:14:24
【问题描述】:
已对此进行了更新,以澄清问题,以便将来更好地帮助其他人。
我正在尝试使用 if 语句来测试密钥 classes 是否存在于使用 Python 的 JSON 结构中。使用 Python 检查 JSON 结构中是否存在密钥。我能够得到密钥,但需要帮助找出条件应该是什么以检查它是否存在。
当它存在于 JSON 结构中时,我使用以下代码成功地返回了键 class 的值:
#Parameter: json_data - The JSON structure it is checking
def parse_classes(json_data):
lst = list()
if('classes' is in json_data['images'][0]['classifiers'][0]): #This doesn't work
for item in json_data['images'][0]['classifiers'][0]['classes']:
lst.append(item['class'])
else:
lst = None
return(lst)
示例json_data:
{"images": ["classifiers": ["classes": ["class": "street"]]]}
我的问题似乎在第 4 行,问题似乎是条件语句不正确。我需要对 if 语句进行哪些更改才能使其正常工作?
【问题讨论】:
-
for item in json_data['images'][0]['classifiers'][0]['classes']: 不应该是for item in classes吗? -
你需要检查
len(json_data['images']),然后检查len(json_data['images'][0]['classifiers']) -
您的屏幕截图与您发布的代码不匹配(类的引号与无引号)。我首先编辑它,但 cmd 回答让我回滚。
-
它不起作用,那么它如何使用或不使用引号?
标签: python json if-statement conditional conditional-statements