Skip to content

Instantly share code, notes, and snippets.

@jmackie
Last active June 10, 2018 20:50
Show Gist options
  • Save jmackie/182c8a0eea49f14409254177aba66365 to your computer and use it in GitHub Desktop.
Save jmackie/182c8a0eea49f14409254177aba66365 to your computer and use it in GitHub Desktop.
Dev.to post
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson ((.:))
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy.Char8 as ByteString
import qualified Network.HTTP as HTTP
import qualified System.IO as IO
main :: IO.IO ()
main = decodePosts <$> fetchPosts >>= \case
Left err -> IO.hPutStrLn IO.stderr err
Right posts -> IO.print (length posts)
fetchPosts :: IO ByteString.ByteString
fetchPosts = do
response <- HTTP.simpleHTTP (HTTP.getRequest url)
HTTP.getResponseBody response <&> ByteString.pack
where url = "http://jsonplaceholder.typicode.com/posts"
decodePosts :: ByteString.ByteString -> Either String [Post]
decodePosts = Aeson.eitherDecode'
data Post = Post
{ userID :: Int
, postID :: Int
, title :: String
, body :: String
}
instance Aeson.FromJSON Post where
parseJSON = Aeson.withObject "Post" $ \v -> Post
<$> v .: "userId"
<*> v .: "id"
<*> v .: "title"
<*> v .: "body"
(<&>) = flip fmap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment