返回具有多个实例的嵌套JSON项 [英] Return nested JSON item that has multiple instances

查看:271
本文介绍了返回具有多个实例的嵌套JSON项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我能够返回几乎所有数据,除了我无法捕获这样的东西:

So i am able to return almost all data, except i am not able to capture something like this:

 "expand": "schema"
  "issues": [
    {
      "expand": "<>",
      "id": "<>",
      "self": "<>",
      "key": "<>",
      "fields": {
        "components": [
          {
            "self": "<>",
            "id": "1",
            "name": "<>",
            "description": "<>"
          }
        ]
      }
    },
    {
      "expand": "<>",
      "id": "<>",
      "self": "<>",
      "key": "<>",
      "fields": {
        "components": [
          {
            "self": "<>",
            "id": "<>",
            "name": "<>"
          }
        ]
      }
    },

我想返回一个包含两个组件"名称的列表,我尝试使用:

I want to return a list that contains both of the 'name's for 'components', i have tried using:

 list((item['fields']['components']['name']) for item in data['issues'])

但是当我尝试Print()上面的代码行时出现类型错误TypeError: list indices must be integers or slices, not str

but i get a type error saying TypeError: list indices must be integers or slices, not str when i try to Print() the above line of code

此外,如果我能对这种类型错误的含义以及列表"正在尝试执行的操作做出一些解释,则意味着它不是值得理解的"str"

Also, if i could get some explanation of what this type error means, and what "list" is trying to do that means that it is not a "str" that would be appreciated

url = '<url>'
r = http.request('GET', url, headers=headers)
data = json.loads(r.data.decode('utf-8'))

print([d['name'] for d in item['fields']['components']] for item in data['issues'])

推荐答案

正如评论者指出的那样,您将列表视为字典,相反,这将从列表中的字典中选择name字段:

As the commenter points out you're treating the list like a dictionary, instead this will select the name fields from the dictionaries in the list:

list((item['fields']['components'][i]['name'] for i, v in enumerate(item['fields']['components'])))

或者简单地:

[d['name'] for d in item['fields']['components']]

然后,您需要将以上内容应用于迭代器中的所有项目.

You'd then need to apply the above to all the items in the iterable.

假设问题"是某些较大词典结构中的键,则仅打印name字段的完整解决方案:

Full solution to just print the name fields, assuming that "issues" is a key in some larger dictionary structure:

for list_item in data["issues"]: # issues is a list, so iterate through list items
    for dct in list_item["fields"]["components"]: # each list_item is a dictionary
        print(dct["name"]) # name is a field in each dictionary

这篇关于返回具有多个实例的嵌套JSON项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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