Last active
September 30, 2016 15:23
-
-
Save Gonzih/84890251c6574211fe77 to your computer and use it in GitHub Desktop.
Aeson HN example of nested JSON (unoptimized binary ~20 mb)
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 OverloadedStrings #-} | |
import Data.Aeson | |
import Control.Applicative ((<$>), (<*>)) | |
import Control.Monad (mzero) | |
import Network.HTTP.Conduit | |
import Data.ByteString.Lazy.Internal (ByteString(..)) | |
data Item = Item { title :: String | |
, url :: String | |
, id :: Float | |
, commentCount :: Float | |
, points :: Float | |
, postedAgo :: Maybe String | |
, postedBy :: Maybe String | |
} deriving (Show) | |
data Feed = Feed { nextId :: Maybe String | |
, items :: [Item] | |
, version :: String | |
, cachedOnUTC :: String | |
} deriving (Show) | |
instance FromJSON Item where | |
parseJSON (Object v) = Item | |
<$> v .: "title" | |
<*> v .: "url" | |
<*> v .: "id" | |
<*> v .: "commentCount" | |
<*> v .: "points" | |
<*> v .: "postedAgo" | |
<*> v .: "postedBy" | |
parseJSON _ = mzero | |
instance FromJSON Feed where | |
parseJSON (Object v) = Feed | |
<$> v .: "nextId" | |
<*> v .: "items" | |
<*> v .: "version" | |
<*> v .: "cachedOnUTC" | |
parseJSON _ = mzero | |
jsonData :: IO Data.ByteString.Lazy.Internal.ByteString | |
jsonData = simpleHttp "http://api.ihackernews.com/page" | |
main :: IO () | |
main = do | |
string <- jsonData | |
let feed = decode string :: Maybe Feed | |
case feed of | |
Just parsedFeed -> print $ map url $ items parsedFeed | |
a -> print a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment