Skip to content

Instantly share code, notes, and snippets.

@Decoherence
Last active August 29, 2015 14:12
Show Gist options
  • Save Decoherence/81718b4fa1f2b748d7f9 to your computer and use it in GitHub Desktop.
Save Decoherence/81718b4fa1f2b748d7f9 to your computer and use it in GitHub Desktop.
Haskell: Quick JSON Parse using Aeson
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