Last active
August 29, 2015 14:12
-
-
Save Decoherence/81718b4fa1f2b748d7f9 to your computer and use it in GitHub Desktop.
Haskell: Quick JSON Parse using 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
import Data.ByteString.Lazy.Internal | |
import Data.Aeson | |
import Control.Applicative | |
data Person = Person String Int deriving (Show) | |
instance FromJSON Person where | |
parseJSON (Object p) = | |
Person <$> | |
(p .: "name") <*> | |
(p .: "age") | |
decode (packChars "{\"name\": \"Chris\", \"age\": 30}") :: Maybe Person | |
--> Just (Person "Chris" 30) | |
instance ToJSON Person where | |
toJSON (Person name age) = | |
object [ "name" .= name | |
, "age" .= age | |
] | |
encode $ Just (Person "Chris" 30) | |
--> "{\"age\":30,\"name\":\"Chris\"}" | |
-- Let's decode an encoded Person to make sure we get back the same thing | |
decode $ encode $ Just $ Person "Chris" 30 :: Maybe Person | |
--> Just (Person "Chris" 30) -- yep! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment