Created
February 13, 2015 04:07
-
-
Save Sam-Serpoosh/6d95683b1e9c19592597 to your computer and use it in GitHub Desktop.
Sample code for JSON parsing using Aeson in Haskell! From the blog post -> http://blog.raynes.me/blog/2012/11/27/easy-json-parsing-in-haskell-with-aeson/
This file contains hidden or 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 #-} | |
module PraseJsonSample where | |
import Data.Aeson ((.:), (.:?), decode, FromJSON(..), Value(..)) | |
import Control.Applicative ((<$>), (<*>)) | |
import Data.Time.Format (parseTime) | |
import Data.Time.Clock (UTCTime) | |
import System.Locale (defaultTimeLocale) | |
import Control.Monad (liftM) | |
import qualified Data.HashMap.Strict as HM | |
import qualified Data.ByteString.Lazy.Char8 as BS | |
parseRHTime :: String -> Maybe UTCTime | |
parseRHTime = parseTime defaultTimeLocale "%FT%X%QZ" | |
data Paste = Paste { getLines :: Integer | |
, getDate :: Maybe UTCTime | |
, getID :: String | |
, getLanguage :: String | |
, getPrivate :: Bool | |
, getURL :: String | |
, getUser :: Maybe String | |
, getBody :: String | |
} deriving (Show) | |
instance FromJSON Paste where | |
parseJSON (Object v) = | |
Paste <$> | |
(v .: "lines") <*> | |
liftM parseRHTime (v .: "date") <*> | |
(v .: "paste-id") <*> | |
(v .: "language") <*> | |
(v .: "private") <*> | |
(v .: "url") <*> | |
(v .:? "user") <*> | |
(v .: "contents") | |
sampleJson :: String | |
sampleJson = "{\"lines\":1,\"date\":\"2012-01-04T01:44:22.964Z\",\"paste-id\":\"1\",\"fork\":null,\"random-id\":\"f1fc1181fb294950ca4df7008\",\"language\":\"Clojure\",\"private\":false,\"url\":\"https://www.refheap.com/paste/1\",\"user\":\"raynes\",\"contents\":\"(begin)\"}" | |
main :: IO () | |
main = do | |
let (Just paste) = decode $ BS.pack sampleJson | |
putStrLn $ show $ getDate paste | |
putStrLn $ show $ getLines paste |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment