on master help sign in
Merge pull request #69 from basvandijk/eitherDecode
43ea36dBryan O'Sullivan
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(..)
@@ -46,7 +48,7 @@ module Data.Aeson
46 ) where
48 ) where
47
49
48import Data.Aeson.Encode (encode)
50import Data.Aeson.Encode (encode)
49−import Data.Aeson.Parser.Internal (decodeWith, json, json')
51+import Data.Aeson.Parser.Internal (decodeWith, eitherDecodeWith, json, json')
50import Data.Aeson.Types
52import Data.Aeson.Types
51import qualified Data.ByteString.Lazy as L
53import qualified Data.ByteString.Lazy as L
52
54
@@ -69,3 +71,13 @@ decode = decodeWith json fromJSON
69decode' :: (FromJSON a) => L.ByteString -> Maybe a
71decode' :: (FromJSON a) => L.ByteString -> Maybe a
70decode' = decodeWith json' fromJSON
72decode' = decodeWith json' fromJSON
71{-# INLINE decode' #-}
73{-# INLINE decode' #-}
74+
75+-- | Like 'decode' but returns an error message when decoding fails.
76+eitherDecode :: (FromJSON a) => L.ByteString -> Either String a
77+eitherDecode = eitherDecodeWith json fromJSON
78+{-# INLINE eitherDecode #-}
79+
80+-- | Like 'decode'' but returns an error message when decoding fails.
81+eitherDecode' :: (FromJSON a) => L.ByteString -> Either String a
82+eitherDecode' = eitherDecodeWith json' fromJSON
83+{-# 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