返回具有多个实例的嵌套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