on master help sign in
Added eitherDecode and eitherDecode'
83078eaBas van Dijk
Data/Aeson.hs+13−1
@@ -16,6 +16,8 @@ module Data.Aeson
16 -- * Encoding and decoding
16 -- * Encoding and decoding
17 decode
17 decode
18 , decode'
18 , decode'
19+ , eitherDecode
20+ , eitherDecode'
19 , encode
21 , encode
20 -- * Core JSON types
22 -- * Core JSON types
21 , Value(..)
23 , Value(..)
@@ -40,7 +42,7 @@ module Data.Aeson
40 ) where
42 ) where
41
43
42import Data.Aeson.Encode (encode)
44import Data.Aeson.Encode (encode)
43−import Data.Aeson.Parser.Internal (decodeWith, json, json')
45+import Data.Aeson.Parser.Internal (decodeWith, eitherDecodeWith, json, json')
44import Data.Aeson.Types
46import Data.Aeson.Types
45import qualified Data.ByteString.Lazy as L
47import qualified Data.ByteString.Lazy as L
46
48
@@ -63,3 +65,13 @@ decode = decodeWith json fromJSON
63decode' :: (FromJSON a) => L.ByteString -> Maybe a
65decode' :: (FromJSON a) => L.ByteString -> Maybe a
64decode' = decodeWith json' fromJSON
66decode' = decodeWith json' fromJSON
65{-# INLINE decode' #-}
67{-# INLINE decode' #-}
68+
69+-- | Like 'decode' but returns an error message when decoding fails.
70+eitherDecode :: (FromJSON a) => L.ByteString -> Either String a
71+eitherDecode = eitherDecodeWith json fromJSON
72+{-# INLINE eitherDecode #-}
73+
74+-- | Like 'decode'' but returns an error message when decoding fails.
75+eitherDecode' :: (FromJSON a) => L.ByteString -> Either String a
76+eitherDecode' = eitherDecodeWith json' fromJSON
77+{-# INLINE eitherDecode' #-}
Data/Aeson/Parser/Internal.hs+10
@@ -23,6 +23,7 @@ module Data.Aeson.Parser.Internal
23 , value'
23 , value'
24 -- * Helpers
24 -- * Helpers
25 , decodeWith
25 , decodeWith
26+ , eitherDecodeWith
26 ) where
27 ) where
27
28
28import Blaze.ByteString.Builder (fromByteString, toByteString)
29import Blaze.ByteString.Builder (fromByteString, toByteString)
@@ -238,6 +239,15 @@ decodeWith p to s =
238 _ -> Nothing
239 _ -> Nothing
239{-# INLINE decodeWith #-}
240{-# INLINE decodeWith #-}
240
241
242+eitherDecodeWith :: Parser Value -> (Value -> Result a) -> L.ByteString -> Either String a
243+eitherDecodeWith p to s =
244+ case L.parse p s of
245+ L.Done _ v -> case to v of
246+ Success a -> Right a
247+ Error msg -> Left msg
248+ L.Fail _ _ msg -> Left msg
249+{-# INLINE eitherDecodeWith #-}
250+
241-- $lazy
251-- $lazy
242--
252--
243-- The 'json' and 'value' parsers decouple identification from
253-- The 'json' and 'value' parsers decouple identification from