Created
December 22, 2015 01:13
-
-
Save nkpart/ec1b289d4670cef8c2f4 to your computer and use it in GitHub Desktop.
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 NoMonomorphismRestriction #-} | |
{-# LANGUAGE OverloadedStrings #-} | |
module Data.Yaml.Extended (module Data.Yaml.Extended, lift) where | |
import Data.Aeson.Types | |
import qualified Data.Text as T | |
import Control.Monad.State.Strict (StateT, runStateT, unless, lift, get, modify) | |
import qualified Data.HashMap.Strict as HM (null, delete, keys) | |
import Data.List (intercalate) | |
prependFailure :: String -> Parser a -> Parser a | |
prependFailure s = modifyFailure (s ++ ) | |
-------------- | |
-- Functions for consuming all keys from an Object | |
useKey :: FromJSON v => T.Text -> StateT Object Parser v | |
useKey k = do o <- get | |
v <- lift (o .: k) | |
modify (HM.delete k) | |
return v | |
failUnlessEmpty :: StateT Object Parser x -> Object -> Parser x | |
failUnlessEmpty sm o = do (x, o') <- runStateT sm o | |
unless (HM.null o') (failWithExtra (HM.keys o')) | |
return x | |
failWithExtra :: (Monad m, Show a) => [a] -> m () | |
failWithExtra unused = fail ("Unhandled fields in JSON object: " ++ v unused) | |
where v = intercalate ", " . map show | |
---------------- | |
ex1 :: Object -> Parser (String, Int) | |
ex1 = failUnlessEmpty $ do v <- useKey "name" | |
x <- useKey "age" | |
return (v, x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment