-1

I am writing some code with Python and Spotipy and I'm relatively new to coding. I have some code that get all the info about a Spotify playlist and prints it out for me:

from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
import json


client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

playlist_id = 'spotify:playlist:76CVeJDw2b90up5PgkZXyU'
results = sp.playlist(playlist_id)
#print(json.dumps(results, indent=4))
print((json.dumps(results, indent=4)))

It works well and gives me all the info. My problem is that I only need specifics from the print:

  "collaborative": false,
    "description": "",
    "external_urls": {
        "spotify": "https://open.spotify.com/playlist/76CVeJDw2b90up5PgkZXyU"
    },
    "followers": {
        "href": null,
        "total": 0
    },
    "href": "https://api.spotify.com/v1/playlists/76CVeJDw2b90up5PgkZXyU?additional_types=track",
    "id": "76CVeJDw2b90up5PgkZXyU",
    "images": [
        {
            "height": 640,
            "url": "https://i.scdn.co/image/ab67616d0000b2734a052b99c042dc15f933145b",
            "width": 640
        }
    ],
    "name": "TEST",
    "owner": {
        "display_name": "Name",
        "external_urls": {
            "spotify": "https://open.spotify.com/user/myname"
        },
        "href": "https://api.spotify.com/v1/users/myname",
        "id": "Myname",
        "type": "user",
        "uri": "spotify:user:kovizsombor"
    },
    "primary_color": null,
    "public": true,
    "snapshot_id": "MixmMGE0MDgxNDQ1ZGVlNmE4MThiMmQwODMwYWU0OTI3YzkyOGJhOWIz",
    "tracks": {
        "href": "https://api.spotify.com/v1/playlists/76CVeJDw2b90up5PgkZXyU/tracks?offset=0&limit=100&additional_types=track",
        "items": [
            {
                "added_at": "2020-05-17T10:00:11Z",
                "added_by": {
                    "external_urls": {
                        "spotify": "https://open.spotify.com/user/kovizsombor"
                    },
                    "href": "https://api.spotify.com/v1/users/kovizsombor",
                    "id": "kovizsombor",
                    "type": "user",
                    "uri": "spotify:user:kovizsombor"
                },
                "is_local": false,
                "primary_color": null,
                "track": {
                    "album": {
                        "album_type": "album",
                        "artists": [
                            {
                                "external_urls": {
                                    "spotify": "https://open.spotify.com/artist/0PFtn5NtBbbUNbU9EAmIWF"
                                },
                                "href": "https://api.spotify.com/v1/artists/0PFtn5NtBbbUNbU9EAmIWF",
                                "id": "0PFtn5NtBbbUNbU9EAmIWF",
                                "name": "TOTO",
                                "type": "artist",
                                "uri": "spotify:artist:0PFtn5NtBbbUNbU9EAmIWF"
                            }
                        ],

                        ],
                        "external_urls": {
                            "spotify": "https://open.spotify.com/album/62U7xIHcID94o20Of5ea4D"
                        },
                        "href": "https://api.spotify.com/v1/albums/62U7xIHcID94o20Of5ea4D",
                        "id": "62U7xIHcID94o20Of5ea4D",
                        "images": [
                            {
                                "height": 640,
                                "url": "https://i.scdn.co/image/ab67616d0000b2734a052b99c042dc15f933145b",
                                "width": 640
                            },
                            {
                                "height": 300,
                                "url": "https://i.scdn.co/image/ab67616d00001e024a052b99c042dc15f933145b",
                                "width": 300
                            },
                            {
                                "height": 64,
                                "url": "https://i.scdn.co/image/ab67616d000048514a052b99c042dc15f933145b",
                                "width": 64
                            }
                        ],
                        "name": "Toto IV",
                        "release_date": "1982-04-08",
                        "release_date_precision": "day",
                        "total_tracks": 10,
                        "type": "album",
                        "uri": "spotify:album:62U7xIHcID94o20Of5ea4D"
                    },
                    "artists": [
                        {
                            "external_urls": {
                                "spotify": "https://open.spotify.com/artist/0PFtn5NtBbbUNbU9EAmIWF"
                            },
                            "href": "https://api.spotify.com/v1/artists/0PFtn5NtBbbUNbU9EAmIWF",
                            "id": "0PFtn5NtBbbUNbU9EAmIWF",
                            "name": "TOTO",
                            "type": "artist",
                            "uri": "spotify:artist:0PFtn5NtBbbUNbU9EAmIWF"
                        }
                    ],
                    "available_markets": [

                    ],
                    "disc_number": 1,
                    "duration_ms": 295893,
                    "episode": false,
                    "explicit": false,
                    "external_ids": {
                        "isrc": "USSM19801941"
                    },
                    "external_urls": {
                        "spotify": "https://open.spotify.com/track/2374M0fQpWi3dLnB54qaLX"
                    },
                    "href": "https://api.spotify.com/v1/tracks/2374M0fQpWi3dLnB54qaLX",
                    "id": "2374M0fQpWi3dLnB54qaLX",
                    "is_local": false,
                    "name": "Africa",
                    "popularity": 83,
                    "preview_url": "https://p.scdn.co/mp3-preview/dd78dafe31bb98f230372c038a126b8808f9349b?cid=d568e7073a38465bba48268ea9f10153",
                    "track": true,
                    "track_number": 10,
                    "type": "track",
                    "uri": "spotify:track:2374M0fQpWi3dLnB54qaLX"
                },
                "video_thumbnail": {
                    "url": null
                }
            }
        ],
        "limit": 100,
        "next": null,
        "offset": 0,
        "previous": null,
        "total": 1
    },
    "type": "playlist",
    "uri": "spotify:playlist:76CVeJDw2b90up5PgkZXyU"
}

From this long print I somehow need to extract the Artist and the song title and preferably make it into a variable. Also not sure how this would work if there are multiple songs in a playlist.

It's also a solution if I can print out only the Artist and the title of the song without printing out all the information.

halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

0

sp.playlist returns a dictionary, so you can simply access its values by their keys. For example:

>>> results['name']
'TEST'

JSON is a data serialization format, ie a standardized way of representing objects as pure text and parsing them back from the text. json.dumps therefore converts the dictionary object to a string of text. This is useful if you want to for example save the results to a file and load it back later. You don't need it to access contents from results.

(This is a playlist though—you will need to get information on each song/track to get its artist and name.)

xcmkz
  • 677
  • 4
  • 15
  • I see.Could I also use sp.playlist_tracks somehow? Seems like it wold be what I need but I just can't understand how could I use it. – Zsombor Kövi May 17 '20 at 13:36
  • Yes -- you need to play a bit with the return value though to make sense of it. For example, if you call `res = sp.playlist_tracks(playlist_id)`, then `tracks['items'][0]['track']['artists'][0]['name']` (meaning the name of the 0th artist of the track of 0th item in the list) would return `"TOTO"`. If the library documentation isn't clear, your best shot will be to play with the output and try to make sense of it. – xcmkz May 17 '20 at 13:44
0

Based on your posted example it appears that you have only 1 song named "Africa" by artist "TOTO". Copying the track to have two songs, I added another track with two artists for testing the arrays.

If that json is loaded into a variable named results then (as @xcmkz said) you have a python dictionary and can process accordingly.

Try working with the following to transverse through your dict appending artists and songs to lists:

song_dict = {}
for track in results['tracks']['items']:
    song_name = track["track"]["name"]
    a2 = []
    for t1 in track['track']['artists']:
        a2.append(t1['name'])
        song_dict.update({song_name: a2})

print(f'Dictionary of Songs and Artists:')
for k, v in song_dict.items():
    print(f'Song --> {k}, by --> {", ".join(v)}')

Results:

Dictionary of Songs and Artists:
Song --> Africa, by --> TOTO
Song --> Just Another Silly Song, by --> Artist 2, Artist 3
DaveStSomeWhere
  • 2,475
  • 2
  • 22
  • 19
  • Thank you it worked like a charm. :) Another silly question since I am really REALLY new to coding. How could I make a variable out of the listed songs which variable I can later plot in to another code? – Zsombor Kövi May 17 '20 at 17:37
  • The listed songs are in a dictionary called song_dict and you can access them the same way I do to print the results. The dictionary contains key, value pairs and that is why the loop uses the variables "k" and "v", where "k" is a string for song title and "v" is a list for 1 to many artists. – DaveStSomeWhere May 17 '20 at 20:09
  • Thank you so much for your time and effort! – Zsombor Kövi May 17 '20 at 20:35