Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Parsing spotify json in Haskell
{-# LANGUAGE OverloadedStrings #-}
module SpotifyPack
import qualified Network.URI as URI
import Network.HTTP (simpleHTTP, getRequest, getResponseBody)
import Data.Aeson (FromJSON, parseJSON, decode, (.:))
import qualified Data.Aeson.Types as T
import qualified Data.ByteString.Lazy.Char8 as BSL
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
data Song = Song { label :: String, duration :: Float }
deriving (Show, Eq, Ord)
searchURL :: String -> String
searchURL term = "" ++
URI.escapeURIString (not . URI.isReserved) term
-- Fetch Songs from Spotify's search API
searchSpotify :: String -> IO (Maybe [Song])
searchSpotify term = do
response <- simpleHTTP $ getRequest $ searchURL term
body <- getResponseBody response
return . parseResponse $ BSL.pack body
instance FromJSON Song where
parseJSON (T.Object v) = Song <$> v .: "name" <*> v.: "length"
parseJSON _ = mzero
-- Helped by
parseResponse :: BSL.ByteString -> Maybe [Song]
parseResponse resp =
do result <- decode resp
flip T.parseMaybe result $ \obj ->
parseJSON =<< (obj .: "tracks")

This comment has been minimized.

Copy link
Owner Author

purcell commented Feb 13, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.