on master help sign in
Merge pull request #69 from basvandijk/eitherDecode

Added eitherDecode and eitherDecode'

commit43ea36d090c2bd13ab97297e48011737e95aaa3e authorBryan O'Sullivan <bos@serpentine.com> dateMon 19 Nov 2012, 20:34 (14 years ago) parente3babd583078ea
2 files changed+23−1
Data/Aeson.hs+13−1 Data/Aeson/Parser/Internal.hs+10
Data/Aeson.hs+13−1
@@ -16,6 +16,8 @@ module Data.Aeson
1616 -- * Encoding and decoding
1717 decode
1818 , decode'
19+ , eitherDecode
20+ , eitherDecode'
1921 , encode
2022 -- * Core JSON types
2123 , Value(..)
@@ -46,7 +48,7 @@ module Data.Aeson
4648 ) where
4749
4850import Data.Aeson.Encode (encode)
49−import Data.Aeson.Parser.Internal (decodeWith, json, json')
51+import Data.Aeson.Parser.Internal (decodeWith, eitherDecodeWith, json, json')
5052import Data.Aeson.Types
5153import qualified Data.ByteString.Lazy as L
5254
@@ -69,3 +71,13 @@ decode = decodeWith json fromJSON
6971decode' :: (FromJSON a) => L.ByteString -> Maybe a
7072decode' = decodeWith json' fromJSON
7173{-# 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
2323 , value'
2424 -- * Helpers
2525 , decodeWith
26+ , eitherDecodeWith
2627 ) where
2728
2829import Blaze.ByteString.Builder (fromByteString, toByteString)
@@ -238,6 +239,15 @@ decodeWith p to s =
238239 _ -> Nothing
239240{-# INLINE decodeWith #-}
240241
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+
241251-- $lazy
242252--
243253-- The 'json' and 'value' parsers decouple identification from