Skip to content

Instantly share code, notes, and snippets.

@madnight
Forked from Gonzih/hn-aeson.hs
Created September 30, 2016 15:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madnight/4d7529ccf05a95a2a3d846ec56fff0de to your computer and use it in GitHub Desktop.
Save madnight/4d7529ccf05a95a2a3d846ec56fff0de to your computer and use it in GitHub Desktop.
Aeson HN example of nested JSON (unoptimized binary ~20 mb)
{-# 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