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

2024-09-29 07:35:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我在过滤多个json数据时遇到了一些困难,我需要知道每个数据的type,如果类型对应于一个水果,那么打印元素的fields键,请参阅python示例注释以获得更好的解释。在

以下是JSON的外观:

#json.items()

{
  'type': 'apple', 
  'fields': {
    'protein': '18g', 
    'glucide': '3%', 
   }
},  
{
  'type': 'banana', 
  'fields': {
    'protein': '22g', 
    'glucide': '8%', 
  }
}, 

我试着这么做:

^{pr2}$

我有办法做到吗?在


Tags: 数据json元素示例类型applefieldstype
2条回答

根据您对JSON的表示,它实际上是一个列表,而不是字典。所以为了遍历它,你可以尝试这样的方法:

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']))

你所拥有的似乎是一系列名言。在

然后检查键type和{}是否存在于字典中,然后再检查它们的值,如下所示:

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

相关问题 更多 >