Last active
August 29, 2015 14:02
-
-
Save jtpaasch/9cb5fbb9750be777bfa3 to your computer and use it in GitHub Desktop.
Encode and decode some simple JSON with the Aeson library.
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 #-} | |
-- We need all of these. | |
import Data.Aeson | |
import Control.Applicative | |
import Control.Monad | |
import qualified Data.ByteString.Lazy.Char8 as BSL | |
-- Create a haskell data type called `Person`. | |
-- Persons have a name and an age. | |
-- They can also be shown on the screen. | |
data Person = Person { name :: String | |
, age :: Int | |
} deriving (Show) | |
-- Define a `FromJSON` functor. This takes a JSON | |
-- string, and parses it into a haskell Person instance | |
-- by finding "name" and "age" in the JSON string and | |
-- putting those in the Person object. | |
instance FromJSON Person where | |
parseJSON (Object v) = Person <$> v .: "name" | |
<*> v .: "age" | |
parseJSON _ = mzero | |
-- Define a `ToJSON` functor. This takes a haskell | |
-- Person instance and converts it to an object | |
-- with "name" and "age" properties, which in turn | |
-- gets converted into JSON. | |
instance ToJSON Person where | |
toJSON (Person name age) = object [ "name" .= name | |
, "age" .= age | |
] | |
-- When anybody runs this program, here is | |
-- the main function that gets executed first. | |
main = do | |
-- To decode JSON: | |
-- -------------------------------------------------- | |
-- Get a JSON string (we need something to decode). | |
let json = BSL.pack "{\"name\":\"Joe\",\"age\":12}" | |
-- Parse it into a Person haskell object. This will use | |
-- our `FromJSON` functor to do the magic. | |
let parsed_json = decode json :: Maybe Person | |
-- Get the value of that object as a string representation, | |
-- so we can show it on the screen. | |
let parsed_json_for_display = show parsed_json | |
-- Now put that line on the screen. | |
putStrLn parsed_json_for_display | |
-- Encoding JSON: | |
-- -------------------------------------------------- | |
-- Create an instance of the Person type (we need something to encode). | |
let sally = Person "Sally" 14 | |
-- Encode it. This will use our `ToJSON` functor to do the magic. | |
let encoded_json = encode sally | |
-- Get the encoded json as a string representation | |
-- so we can show it on the screen. | |
let encoded_json_for_display = show encoded_json | |
-- Now put that line on the screen. | |
putStrLn encoded_json_for_display |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment