Skip to content

Instantly share code, notes, and snippets.

@mkscrg
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkscrg/89f36f12446cafb55cc3 to your computer and use it in GitHub Desktop.
Save mkscrg/89f36f12446cafb55cc3 to your computer and use it in GitHub Desktop.
Aeson + REPL
$ cabal sandbox init
$ cabal install aeson
$ ghci
Prelude> :set prompt "> "
> :set -XOverloadedStrings
> :l Deep.hs
[1 of 1] Compiling Deep             ( Deep.hs, interpreted )
Ok, modules loaded: Deep.

> -- some data:
> jsonTxt
"{\"foo\":{\"bar\":{\"baz\":\"deeeeeep\"}}}"

> -- go deep
> decodeP (top >>: "foo" >>: "bar" >>: "baz") jsonTxt :: Either String Text
Right "deeeeeep"

> -- continue parsing at depth
> let checkString = (\s -> when (s /= "quux") (fail $ "unexpected string: " ++ show s)) :: Text -> Parser ()
> decodeP (top >>: "foo" >>: "bar" >>: "baz" >=> checkString) jsonTxt
Left "unexpected string: \"deeeeeep\""
{-# LANGUAGE OverloadedStrings #-}
module Deep where
import Control.Monad
import Data.Aeson
import Data.Aeson.Types
import Data.ByteString.Lazy
import Data.Text
jsonTxt :: ByteString
jsonTxt = "{\"foo\":{\"bar\":{\"baz\":\"deeeeeep\"}}}"
decodeP :: (Value -> Parser a) -> ByteString -> Either String a
decodeP pf lbs = do
jsonVal <- eitherDecode lbs
parseEither (\v -> pf v) jsonVal
top :: FromJSON a => Value -> Parser a
top = parseJSON
(>>:) :: FromJSON a => (b -> Parser Object) -> Text -> (b -> Parser a)
pf >>: key = pf >=> (.: key)
infixl 6 >>:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment