Как получить элемент, вложенный в словарь JSON? - PullRequest
0 голосов
/ 31 марта 2020

Я получил JSON ответ, используя Spotify API, и я пытаюсь получить доступ к элементу под названием «name» (один говорит «3 Doors Down», а другой начинается с «Bret Michaels»), который, кажется, находится внутри элемент 'items', но я не могу найти решение.

Вот как я загружал данные:

search_results = requests.get(search_url + 'q=' + query + '&type=artist', headers=granted_headers).json()

Вот мои JSON данные:

{
  'artists': {
    'href': 'https://api.spotify.com/v1/search?query=3+doors+down&type=artist&offset=0&limit=20',
    'items': [
      {
       'external_urls': {
       'spotify': 'https://open.spotify.com/artist/2RTUTCvo6onsAnheUk3aL9'
      },
      'followers': {
      'href': None,
      'total': 2631330
      },
      'genres': [
        'alternative metal',
        'nu metal',
        'pop rock',
        'post-grunge'
      ],
      'href': 'https://api.spotify.com/v1/artists/2RTUTCvo6onsAnheUk3aL9',
      'id': '2RTUTCvo6onsAnheUk3aL9',
      'images': [
        {
          'height': 640,
          'url': 'https://i.scdn.co/image/ead4e883a59d30d8c157385aa531d3fe8e688fc0',
          'width': 640
        },
        {
          'height': 320,
          'url': 'https://i.scdn.co/image/611a4fd8aaf2637c5894acf65f12e79d75926329',
          'width': 320
        },
        {
          'height': 160,
          'url': 'https://i.scdn.co/image/f1a1a2c37f2f6d242b1ab7ae3f4d893bf5822095',
          'width': 160
        }
      ],
      'name': '3 Doors Down',
      'popularity': 72,
      'type': 'artist',
      'uri': 'spotify:artist:2RTUTCvo6onsAnheUk3aL9'
    },
    {
      'external_urls': {
        'spotify': 'https://open.spotify.com/artist/2kPbQDZvnasPcCuXbq6YQx'
      },
      'followers': {
        'href': None,
        'total': 156
      },
      'genres': [

      ],
      'href': 'https://api.spotify.com/v1/artists/2kPbQDZvnasPcCuXbq6YQx',
      'id': '2kPbQDZvnasPcCuXbq6YQx',
      'images': [

      ],
      'name': 'Bret Michaels (Featuring Brad Arnold of 3 Doors Down, Chris Cagle, Mark Wills)',
      'popularity': 4,
      'type': 'artist',
      'uri': 'spotify:artist:2kPbQDZvnasPcCuXbq6YQx'
    }
  ],
  'limit': 20,
  'next': None,
  'offset': 0,
  'previous': None,
  'total': 4
 }
}

1 Ответ

0 голосов
/ 31 марта 2020
artists = search_results['artists']['items'] # This is a list
for artist in artists: # artist is each object in the list
    print(artist['name'])
Output:
> '3 Doors Down'
> 'Bret Michaels (Featuring Brad Arnold of 3 Doors Down, Chris Cagle, Mark Wills)'
...