使用Python 3检查JSON键是否为空的条件语句
这已经更新,以澄清这个问题,以便它可以更好地帮助其他人在未来使用Python 3检查JSON键是否为空的条件语句,python,json,if-statement,conditional,conditional-statements,Python,Json,If Statement,Conditional,Conditional Statements,这已经更新,以澄清这个问题,以便它可以更好地帮助其他人在未来 我试图使用if语句测试键classes是否存在于使用Python的JSON结构中。使用Python检查JSON结构中是否存在密钥。我可以得到钥匙,但需要帮助找出什么条件应该是检查它是否存在 使用以下代码,我成功地返回了存在于JSON结构中的键class的值: #Parameter: json_data - The JSON structure it is checking def parse_classes(json_data):
我试图使用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\u数据
:
{"images": ["classifiers": ["classes": ["class": "street"]]]}
我的问题似乎在第4行,问题似乎是有条件的陈述是不正确的。要使if语句正确工作,我需要对其进行哪些更改?我想您的意思是
if
,而不是for
:
def parse_classes(json_data):
lst = set()
if 'classes' in json_data['images'][0]['classifiers'][0]:
for item in json_data['images'][0]['classifiers'][0]['classes']:
lst.add(item['class'])
else:
print("")
return lst
还是防守
def parse_classes(json_data):
lst = set()
if (json_data.get('images')
and json_data['images'][0].get('classifiers')
and json_data['images'][0]['classifiers'][0].get('classes')):
for item in json_data['images'][0]['classifiers'][0].get('classes', []):
lst.add(item['class'])
return lst if lst else None
如果要在所有分类器中使用所有类
,请在所有图像中使用所有
def parse_classes(json_data):
lst = set()
for image in json_data.get('images', []):
for classifier in image.get('classifiers', []):
for item in classifier.get('classes', []):
lst.add(item['class'])
return lst if lst else None
对于json_数据['images'][0]['classifiers'][0]['classes']]
:对于类中的项目不应该是吗
?这是一个后续问题,你需要检查len(json_数据['images']]
,然后len(json_数据['images'][0]['classifiers'])
你的屏幕截图与你发布的代码不匹配(对类使用引号vs不使用引号)。我首先编辑了它,但cmd answer让我回滚。它不起作用,那么它如何使用引号或不使用引号?仍然说indexer:List index out-range
它适用于您提供的json数据。您有失败时的数据吗?json_数据['images'][0]['classifiers'][0]
在其中一个子列表中必须为空。无法reproduce@cmd我添加了代码。第二件事仍然显示列表索引超出范围。需要查看完整错误和/或错误数据。