我在过滤多个 json 数据时遇到了一些困难,我需要知道type
每个数据的类型,如果类型对应于水果,则打印元素的fields
键,请参阅 python 示例注释以获得更好的解释。
这是 JSON 的样子:
#json.items()
{
'type': 'apple',
'fields': {
'protein': '18g',
'glucide': '3%',
}
},
{
'type': 'banana',
'fields': {
'protein': '22g',
'glucide': '8%',
}
},
这是我尝试做的:
for key, value in json.items(): #access json dict.
if key == 'type': #access 'type' key
if value == 'apple': #check the fruit
if key == 'fields': #ERROR !!! Now I need to access the 'fields' key datas of this same fruit. !!!
print('What a good fruit, be careful on quantity!')
print('more :' + value['protein'] + ', ' + value['glucid'])
if value == 'banana': #if not apple check for bananas
print('One banana each two days keeps you healthy !')
print('more:' + value['protein'] + ', ' + value['glucid'])
有没有办法实现这一目标?
你所拥有的似乎是一个字典列表。
然后在检查它们的值之前检查键type
和是否fields
存在于字典中,如下所示:
for d in data: # d is a dict
if 'type' in d and 'fields' in d:
if d['type'] == 'apple':
... # some print statements
elif d['type'] == 'banana':
... # some more print statements
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句