如何使用Python过滤多个JSON数据?

如何使用Python过滤多个JSON数据?,python,json,Python,Json,我很难过滤多个json数据,我需要知道每个数据的类型,如果类型对应于一个水果,那么打印元素的字段键,请参阅python示例注释以获得更好的解释 以下是JSON的外观: #json.items() { 'type': 'apple', 'fields': { 'protein': '18g', 'glucide': '3%', } }, { 'type': 'banana', 'fields': { 'protein': '22g',

我很难过滤多个json数据,我需要知道每个数据的类型,如果类型对应于一个水果,那么打印元素的字段键,请参阅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'])

我有什么办法可以做到这一点吗?

你所拥有的似乎是一份口述清单

然后,检查字典中是否存在键类型和字段,然后再检查其值,如下所示:

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
for item in json:
    fields = item['fields']
    if item['type'] == 'banana':
        print('Bananas have {} of protein and {} glucide'.format(fields['protein'], fields['glucide']))
    elif item['type'] == 'apple':
        print('Apples have {} of protein and {} glucide'.format(fields['protein'], fields['glucide']))

根据您对JSON的表示,它看起来实际上是一个列表,而不是一个字典。因此,为了遍历它,您可以尝试以下方法:

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
for item in json:
    fields = item['fields']
    if item['type'] == 'banana':
        print('Bananas have {} of protein and {} glucide'.format(fields['protein'], fields['glucide']))
    elif item['type'] == 'apple':
        print('Apples have {} of protein and {} glucide'.format(fields['protein'], fields['glucide']))

如果您发布的是整个json,那么您有一个dict列表,而不仅仅是一个dict。您需要两个循环。@cᴏʟᴅsᴘᴇᴇᴅ 我发布的内容与我的json完全不同,因为它有太多的数据,这一条经过了简化,因此更容易理解,但“fruit”varySo打印出json的数量给了你一个这些内容的列表?你的第一条和第三条if永远不会同时为真。@KlausD。是的,我看到了,这就是为什么我问这个问题的原因,这是有效的!出于使用目的,是否可以不在if语句和循环中为所有现有键指定每个键?@Lindow如果您想为每个项打印唯一的语句,我认为这是不可能的。@Lindow如果您有一个通用的打印语句而没有其他内容,您可以删除ifs,只打印类似于print{s have{}的内容蛋白质和{}糖类。formatd['type'],d['fields']['protein'],d['fields']['glucide']