Last active
June 10, 2018 20:50
-
-
Save jmackie/182c8a0eea49f14409254177aba66365 to your computer and use it in GitHub Desktop.
Dev.to post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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