Commits

basvandijk committed 66262a5

Added eitherDecode and eitherDecode'
They are just like decode and decode' respectively
but return an error message when decoding fails.

  • Participants
  • Parent commits 216ae7f

Comments (0)

Files changed (2)

     -- * Encoding and decoding
       decode
     , decode'
+    , eitherDecode
+    , eitherDecode'
     , encode
     -- * Core JSON types
     , Value(..)
     ) where
 
 import Data.Aeson.Encode (encode)
-import Data.Aeson.Parser.Internal (decodeWith, json, json')
+import Data.Aeson.Parser.Internal (decodeWith, eitherDecodeWith, json, json')
 import Data.Aeson.Types
 import qualified Data.ByteString.Lazy as L
 
 decode' :: (FromJSON a) => L.ByteString -> Maybe a
 decode' = decodeWith json' fromJSON
 {-# INLINE decode' #-}
+
+-- | Like 'decode' but returns an error message when decoding fails.
+eitherDecode :: (FromJSON a) => L.ByteString -> Either String a
+eitherDecode = eitherDecodeWith json fromJSON
+{-# INLINE eitherDecode #-}
+
+-- | Like 'decode'' but returns an error message when decoding fails.
+eitherDecode' :: (FromJSON a) => L.ByteString -> Either String a
+eitherDecode' = eitherDecodeWith json' fromJSON
+{-# INLINE eitherDecode' #-}

Data/Aeson/Parser/Internal.hs

     , value'
     -- * Helpers
     , decodeWith
+    , eitherDecodeWith
     ) where
 
 import Blaze.ByteString.Builder (fromByteString, toByteString)
       _          -> Nothing
 {-# INLINE decodeWith #-}
 
+eitherDecodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Either String a
+eitherDecodeWith p to s =
+    case L.parse p s of
+      L.Done _ v -> case to v of
+                      Success a -> Right a
+                      Error msg -> Left msg
+      L.Fail _ _ msg -> Left msg
+{-# INLINE eitherDecodeWith #-}
+
 -- $lazy
 --
 -- The 'json' and 'value' parsers decouple identification from