Python中的Retreive JSON键 [英] Retreive JSON Keys In Python

查看:138
本文介绍了Python中的Retreive JSON键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是遍历classes中的 每个 元素,并将classes中的class的值添加到新列表中.

My goal is to iterate through every element in classes and add the value of class in classes into a new list.

JSON结构:

{
    "images": [
      {
        "classifiers": [
          {
            "classes": [
              {
                "class": "street",
                "score": 0.846
              },
              {
                "class": "road",
                "score": 0.85
              }
            ]
          }
        ]
      }
   ]
}

在上述JSON示例中,新列表应包含:

In the above JSON example, the new list should contain:

{'street','road'}

我尝试遍历json_data['images'][0]['classifiers']['classes'],并为每个list.append()设置class的值.

I tried to iterate over json_data['images'][0]['classifiers']['classes'] and for each one list.append() the value of class.

list = list()
def func(json_data):
    for item in json_data['images'][0]['classifiers']['classes']:
        list.append(item['class'])
    return(list)

我收到的TypeError是:

TypeError: list indices must be integers or slices, not str

我从此TypeError中得到的是,它尝试将字符串添加到列表中,但是list.append()不接受字符串作为参数.我需要以某种方式将字符串转换为其他字符串.

What I am getting from this TypeError is that it attempts to add a string to the list but list.append() does not accept a string as a paramet. I need to somehow convert the string into something else.

我的问题是我应该将字符串转换为什么,以便list.append()接受它作为参数?

My question is what should I convert the string into so that list.append() will accept it as a parameter?

推荐答案

第一个问题是classifiers也是一个列表,因此您需要一个附加索引才能获取classes.这将起作用:

The first issue is that classifiers is also a list, so you need an additional index to get at classes. This will work:

for item in json_data['images'][0]['classifiers'][0]['classes']:

第二,您希望将结果作为集合而不是列表,因此可以执行:return set(lst).请注意,集合是无序的,所以不要期望项目的顺序与列表的顺序相匹配.

Second, you want the result as a set not a list, so you can do: return set(lst). Note that sets are unordered, so don't expect the ordering of items to match that of the list.

这篇关于Python中的Retreive JSON键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆