Home > Software design >  Parse Spotipy results
Parse Spotipy results

Time:06-24

I'm still getting to grips with Spotipy API and JSON - I'm new to both and am a little confused as to how to parse the results from a search.

Let's try looking for a uniquely named track

def get_tracks(tracktitle):

  results   = sp.search(q ="track:"   tracktitle, type = "track")

  for idx, track in enumerate(results["tracks"]["items"]):
    track_id = results["tracks"]["items"][idx]["uri"]
    print(idx, track['name'], track_id)


myTrack = "Leeds road 3am"
get_tracks(myTrack)

This returns

0 Leeds Road 3am spotify:track:4TaPFJ25RdoymYDPNtdwnv

1 Leeds Road 3am spotify:track:4XIPNAIu1cbtQ9gA6APZQ2

So far, so good. Only I want to loop through the resulting JSON object and get the track name, album name and Artist name.

Here's part of the results

      "name": "Eight",
      "release_date": "2000",
      "release_date_precision": "year",
      "total_tracks": 11,
      "type": "album",
      "uri": "spotify:album:1vBvFaEZZezQZLLaEMGvTW"
    },
    "artists": [
      {
        "external_urls": {
          "spotify": "https://open.spotify.com/artist/7n1EM42Fseebd9H2p8eWWS"
        },
        "href": "https://api.spotify.com/v1/artists/7n1EM42Fseebd9H2p8eWWS",
        "id": "7n1EM42Fseebd9H2p8eWWS",
        "name": "New Model Army",
        "type": "artist",
        "uri": "spotify:artist:7n1EM42Fseebd9H2p8eWWS"
      }
    ],...

I've tried

  for idx, track in enumerate(results["tracks"]["items"]):
    # artist   = results["artists"]["item"][idx]["uri"]
    # artist   = results["artists"]["name"][idx]["uri"]
    # artist   = results["tracks"]["items"]["artists"][idx]["uri"]

What I'd like to print

i Track Name Artist Name Album name id

0 Leeds Road 3am New Model Army Eight spotify:track:4TaPFJ25RdoymYDPNtdwnv

1 Leeds Road 3am New Model Army Eight spotify:track:4XIPNAIu1cbtQ9gA6APZQ2

CodePudding user response:

print(idx, track['name'], track['artists'][0]['name'], track['album']['name'], track_id) in the for loop should work. Note that only the first artist name is printed (there can be multiple artists on the same track)

  • Related