Access item in JSON result

后端 未结 3 970
[愿得一人]
[愿得一人] 2021-01-26 15:56

I am a bit confused as to how access artists name in this JSON result:

{
  \"tracks\" : {
    \"href\" : \"https://api.spotify.com/         


        
相关标签:
3条回答
  • 2021-01-26 16:11

    Defensively written, this might look something like:

    artist_names = set() # using a set avoids adding the same name more than once
    if 'tracks' in results and 'items' in results['tracks']:
      for item in results['tracks']['items']:
        for artist in item.get('artists', ()):
          if 'name' in artist:
            artist_names.add(artist['name'])
    
    for name in artist_names:
      print "Found artist:", name
    
    0 讨论(0)
  • 2021-01-26 16:19

    You should do items = results['tracks']['items'][0]['artists'][0]['name'](although this is technically hardcoded)

    As your artist and items object are arrays (with only one, so we reference the first with [0])

    0 讨论(0)
  • 2021-01-26 16:24

    artists is a list of dicts, because a track can have many artists. Similarly items is also a list. So for example you can do results['tracks']['items'][0]['artists'][0]['name'], but that will only get you the first artist of the first track.

    0 讨论(0)
提交回复
热议问题