Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

python - Return nested JSON item that has multiple instances

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

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

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

EDIT:

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'])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Or simply:

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

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

EDIT: 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...