on master help sign in
Fix .:? behavior for #83

It makes (.:?) return Just value if the key is present for values of type Maybe a. Earlier {"key": null} .:? "key" would return Nothing although the key is there. It was not possible to distinguish the cases when key is absent and when value is null. Now it treats Maybe same way as other types and returns Just Nothing.

commitd0414be92ee6bf5b4c057978955b89d111767dab authorBoris Lykah <blykah@stilo.com> dateThu 18 Dec 2014, 13:42 (12 years ago) parent599dc77
3 files changed+7−6
Data/Aeson/TH.hs+3−2 Data/Aeson/Types/Generic.hs+3−3 Data/Aeson/Types/Instances.hs+1−1
Data/Aeson/TH.hs+3−2
@@ -100,7 +100,8 @@ import Data.Aeson.Types ( Value(..), Parser
100100 , defaultTaggedObject
101101 )
102102import Data.Aeson.Types.Internal (Encoding(..))
103−import Data.Bool ( Bool(False, True), otherwise, (&&) , not)
103+import Control.Monad ( return, mapM, liftM2, fail, join )
104+import Data.Bool ( Bool(False, True), otherwise, (&&), not )
104105import Data.Either ( Either(Left, Right) )
105106import Data.Eq ( (==) )
106107import Data.Function ( ($), (.), flip )
@@ -953,7 +954,7 @@ instance (FromJSON a) => LookupField a where
953954 Just v -> parseJSON v
954955
955956instance (FromJSON a) => LookupField (Maybe a) where
956− lookupField _ _ = (.:?)
957+ lookupField _ _ obj key = join <$> obj .:? key
957958
958959unknownFieldFail :: String -> String -> String -> Parser fail
959960unknownFieldFail tName rec key =
Data/Aeson/Types/Generic.hs+3−3
@@ -20,7 +20,7 @@
2020module Data.Aeson.Types.Generic ( ) where
2121
2222import Control.Applicative ((<*>), (<$>), (<|>), pure)
23−import Control.Monad ((<=<))
23+import Control.Monad ((<=<), join)
2424import Control.Monad.ST (ST)
2525import Data.Aeson.Encode.Builder (emptyArray_)
2626import Data.Aeson.Encode.Functions (builder)
@@ -656,8 +656,8 @@ instance (Selector s, GFromJSON a) => FromRecord (S1 s a) where
656656 {-# INLINE parseRecord #-}
657657
658658instance (Selector s, FromJSON a) => FromRecord (S1 s (K1 i (Maybe a))) where
659− parseRecord _ (Just lab) obj = (M1 . K1) <$> obj .:? lab
660− parseRecord opts Nothing obj = (M1 . K1) <$> obj .:? pack label
659+ parseRecord _ (Just lab) obj = (M1 . K1) . join <$> obj .:? lab
660+ parseRecord opts Nothing obj = (M1 . K1) . join <$> obj .:? pack label
661661 where
662662 label = fieldLabelModifier opts $
663663 selName (undefined :: t s (K1 i (Maybe a)) p)
Data/Aeson/Types/Instances.hs+1−1
@@ -1525,7 +1525,7 @@ obj .: key = case H.lookup key obj of
15251525(.:?) :: (FromJSON a) => Object -> Text -> Parser (Maybe a)
15261526obj .:? key = case H.lookup key obj of
15271527 Nothing -> pure Nothing
1528− Just v -> parseJSON v <?> Key key
1528+ Just v -> Just <$> parseJSON v <?> Key key
15291529{-# INLINE (.:?) #-}
15301530
15311531-- | Helper for use in combination with '.:?' to provide default