Last active
August 26, 2016 13:07
-
-
Save queertypes/8b2eb8e0fcedb41b4ed2 to your computer and use it in GitHub Desktop.
Parsing with Aeson.
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
-- Inspired by this [scala](https://gist.github.com/ccarter/e91110f76c9c9d1e256d) example: | |
{-# LANGUAGE OverloadedStrings #-} | |
{- | |
A demonstration of Aeson for JSON parsing. We want to take something that looks like: | |
{ | |
"id": 5, | |
"bar": "bar", | |
"baz": "baz" | |
} | |
and map it to a type in-memory, like: | |
Data Entity = Entity Int String String | |
-} | |
module Main where | |
import Data.Aeson | |
import Control.Applicative ((<$>), (<*>)) | |
import Control.Monad (mzero) | |
data Foo = Foo {bar :: String, baz :: String} deriving Show | |
data Entity = Entity {eId :: Int, eFoo :: Foo} deriving Show | |
instance FromJSON Entity where | |
parseJSON (Object v) = do | |
eid <- v .: "id" | |
bar' <- v .: "bar" | |
baz' <- v .: "baz" | |
return $ Entity eid (Foo bar' baz') | |
-- or more succinctly: | |
-- parseJSON (Object v) = | |
-- Entity <$> v .: "id" <*> (Foo <$> v .: "bar" <*> v .: "baz") | |
parseJSON _ = mzero -- failed parse -> Nothing | |
instance ToJSON Entity where | |
toJSON (Entity eid (Foo bar' baz')) = object ["id" .= eid, | |
"bar" .= bar', | |
"baz" .= baz'] | |
main :: IO () | |
main = do | |
let entity = Entity 5 (Foo "bar" "baz") | |
let entityJson = encode entity | |
print entityJson | |
print (decode entityJson :: Maybe Entity) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment