Skip to content

Added eitherDecode and eitherDecode' #69

Merged
merged 1 commit into from Nov 20, 2012
View
14 Data/Aeson.hs
@@ -16,6 +16,8 @@ module Data.Aeson
-- * Encoding and decoding
decode
, decode'
+ , eitherDecode
+ , eitherDecode'
, encode
-- * Core JSON types
, Value(..)
@@ -40,7 +42,7 @@ module Data.Aeson
) 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
@@ -63,3 +65,13 @@ decode = decodeWith json fromJSON
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' #-}
View
10 Data/Aeson/Parser/Internal.hs
@@ -23,6 +23,7 @@ module Data.Aeson.Parser.Internal
, value'
-- * Helpers
, decodeWith
+ , eitherDecodeWith
) where
import Blaze.ByteString.Builder (fromByteString, toByteString)
@@ -238,6 +239,15 @@ decodeWith p to s =
_ -> 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
Something went wrong with that request. Please try again.