【问题标题】:Return nested JSON item that has multiple instances返回具有多个实例的嵌套 JSON 项
【发布时间】:2018-12-06 16:03:39
【问题描述】:

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

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

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

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

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

另外,如果我能解释一下这种类型错误的含义,以及“list”试图做什么,这意味着它不是一个值得赞赏的“str”

编辑:

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

【问题讨论】:

  • item['fields']['components'] 是一个列表。你把它当作一本字典。
  • 只是为了澄清,为什么这是通过添加 list() 的字典?从list((item['fields']['components']['name']) for item in data['issues']) 返回的数据被“ [ ] ”包围,并且通过阅读它,它表示这将被视为一个列表
  • item['fields']['components'] 的值是一个列表:[{"self": "&lt;&gt;", "id": "&lt;&gt;", "name": "&lt;&gt;"}]。该列表的第一个元素是另一个字典,您可以在其中访问name。所以访问该名称的正确方法是:item['fields']['components'][0]['name'] -- 我希望这会有所帮助!

标签: python json


【解决方案1】:

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

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

或者简单地说:

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

然后您需要将上述内容应用于迭代中的所有项目。

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

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

【讨论】:

  • 括号真的可以省略,因为它只是一个列表理解。 [d['name'] for d in item['fields']['components']]
  • 为什么当我尝试print() 这行代码时,它在我的终端中作为生成器对象返回而不是实际名称?
  • 你能发布生成生成器对象的代码吗?
  • 刚刚做了,检查编辑
  • 试试这个:print([[d['name'] for d in v['components']] for k, v in data['issues'].items()])
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 2015-10-28
  • 2021-07-26
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 2020-12-26
相关资源
最近更新 更多