How to Export Your Spotify Playlists to a JSON File Using PowerShell

Page content

How to Export Your Spotify Playlists to a JSON File Using PowerShell

I need to move off Spotify for a specific reason and was looking for a way to move my music lists to other platforms. There are a number of website that can perform this task for you, here I will go over how to export your playlists so you can use them to build up your new collections in other platforms. This script will walk you through how to use PowerShell to connect to the Spotify API, retrieve your playlists, and save them to a JSON file.

Prerequisites

Before diving into the script, you’ll need to set up a few things:

  1. Spotify Developer Account:

    • Go to the Spotify Developer Dashboard and create a new application.
    • Obtain your Client ID and Client Secret from the Spotify Developer Dashboard.
  2. PowerShell:

    • This script uses PowerShell, which is available on most Windows systems. If you’re on Linux or macOS, you can also run PowerShell scripts by installing PowerShell Core.

The Complete PowerShell Script

Here’s a detailed PowerShell script that allows you to authenticate with Spotify, retrieve your playlists, and export them to a JSON file. The script includes comments, error handling, and step-by-step instructions.

# Spotify API Credentials
$clientId = "YourSpotifyClientID"  # Replace with your Client ID
$clientSecret = "YourSpotifyClientSecret"  # Replace with your Client Secret
$redirectUri = "http://localhost:8888/callback"  # Not used in this flow, but needed for completeness

# Step 1: Direct user to Spotify's authorization page
$authUrl = "https://accounts.spotify.com/authorize?response_type=code&client_id=$clientId&redirect_uri=$redirectUri&scope=playlist-read-private%20playlist-read-collaborative"
Write-Output "Please visit the following URL in your browser to authorize the application:"
Write-Output $authUrl

# Step 2: User logs in, approves the app, and receives an authorization code
# The user will be redirected to the specified redirect URI with an authorization code in the query string
# Return URL will be like this, take the part after code and enter it as the code.
# http://localhost:8888/callback?code= xyz

# Step 3: Capture the authorization code manually (you'll need to paste it here)
$authCode = Read-Host -Prompt "Enter the authorization code provided by Spotify"

# Step 4: Exchange the authorization code for an access token
try {
    $tokenResponse = Invoke-RestMethod -Method Post -Uri "https://accounts.spotify.com/api/token" `
        -Headers @{
            Authorization = "Basic " + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("$($clientId):$($clientSecret)"))
        } `
        -Body @{
            grant_type = "authorization_code"
            code = $authCode
            redirect_uri = $redirectUri
        }
    $accessToken = $tokenResponse.access_token
    $refreshToken = $tokenResponse.refresh_token
} catch {
    Write-Error "Failed to retrieve access token: $_"
    exit
}

# Step 5: Get User's Playlists
function Get-SpotifyPlaylists {
    try {
        $playlistsResponse = Invoke-RestMethod -Method Get -Uri "https://api.spotify.com/v1/me/playlists" `
            -Headers @{Authorization = "Bearer $accessToken"}
        return $playlistsResponse.items
    } catch {
        Write-Error "Failed to retrieve Spotify playlists: $_"
        return $null
    }
}

# Retrieve playlists
$playlists = Get-SpotifyPlaylists
if (-not $playlists) {
    Write-Error "No playlists retrieved. Exiting script."
    exit
}

# Initialize an array to store playlist data
$playlistsData = @()

# Iterate through each playlist and collect data
foreach ($playlist in $playlists) {
    try {
        $playlistTracksUrl = $playlist.tracks.href
        $playlistTracksResponse = Invoke-RestMethod -Method Get -Uri $playlistTracksUrl `
            -Headers @{Authorization = "Bearer $accessToken"}

        $playlistData = @{
            Name = $playlist.name
            Id = $playlist.id
            Tracks = $playlistTracksResponse.items | ForEach-Object {
                @{
                    Name = $_.track.name
                    Artist = $_.track.artists[0].name
                    Album = $_.track.album.name
                }
            }
        }
        $playlistsData += $playlistData
    } catch {
        Write-Error "Failed to retrieve tracks for playlist '$($playlist.name)': $_"
    }
}

# Convert playlists data to JSON
$jsonOutput = $playlistsData | ConvertTo-Json -Depth 3

# Save JSON to a file
$outputFilePath = "d:\temp\spotify_playlists.json"
try {
    $jsonOutput | Out-File -FilePath $outputFilePath -Encoding utf8
    Write-Output "Playlists saved to $outputFilePath"
} catch {
    Write-Error "Failed to save playlists to JSON file: $_"
}

Script Breakdown

Let’s break down the script to understand what each section does:

  1. Spotify API Credentials: The script begins by defining your Spotify API credentials, which are required to authenticate with the Spotify API.

  2. Authorization URL: The script generates a URL that you need to visit in your web browser to authorize the application. After authorizing, Spotify will redirect you to the specified URI with an authorization code.

  3. Capture Authorization Code: After getting redirected, you’ll need to manually paste the authorization code into the script.

  4. Exchange Authorization Code for Access Token: The script exchanges the authorization code for an access token, which is used to make authorized requests to the Spotify API.

  5. Retrieve Playlists: The script uses the access token to fetch all your Spotify playlists. Each playlist is then processed to extract relevant track information.

  6. Collect Playlist Data: The script iterates over each playlist and retrieves track details like name, artist, and album. This data is stored in a structured format.

  7. Convert to JSON: The collected data is then converted to JSON format, making it easy to read and use in other applications.

  8. Save JSON to File: Finally, the JSON data is saved to a file on your local machine. This file can be used later for analysis, backups, or even importing into another music service.

Testing the Script

To ensure everything is working:

  • Replace the placeholders (YourSpotifyClientID, YourSpotifyClientSecret, etc.) with your actual credentials.
  • Run the script in PowerShell.
  • Open the generated JSON file to verify that your playlists were successfully saved.

Error Handling

The script includes error handling using try/catch blocks. If something goes wrong (e.g., network issues, invalid credentials, API limits), the script will log an error message and exit gracefully.

Conclusion

By following the steps outlined in this blog post, you can export your Spotify playlists to a JSON file using PowerShell. This script not only provides a backup of your playlists but also offers a way to analyze and migrate your music collections to other platforms.

Disclaimer

This script is provided with no warranty. Use it at your own risk. Ensure you have the necessary permissions and understand the script before running it.

By using this script, you can easily gather essential information about the licensing status of your Windows hosts, making it a valuable tool for IT administrators and support personnel.