@@ -52,6 +52,7 @@ module Data.Aeson.Types.Instances
5252 , ifromJSON
5353 , (.:)
5454 , (.:?)
55+ , (.:!)
5556 , (.!=)
5657 , tuple
5758 , (>*<)
@@ -1533,7 +1534,7 @@ ifromJSON = iparse parseJSON
15331534--
15341535-- This accessor is appropriate if the key and value /must/ be present
15351536-- in an object for it to be valid. If the key and value are
1536−-- optional, use '(.:?)' instead.
1537+-- optional, use '.:?' instead.
15371538(.:) :: (FromJSON a) => Object -> Text -> Parser a
15381539obj .: key = case H.lookup key obj of
15391540 Nothing -> fail $ "key " ++ show key ++ " not present"
@@ -1549,23 +1550,34 @@ obj .: key = case H.lookup key obj of
15491550--
15501551-- This accessor is most useful if the key and value can be absent
15511552-- from an object without affecting its validity. If the key and
1552−-- value are mandatory, use '(.:)' instead.
1553+-- value are mandatory, use '.:' instead.
15531554(.:?) :: (FromJSON a) => Object -> Text -> Parser (Maybe a)
15541555obj .:? key = case H.lookup key obj of
15551556 Nothing -> pure Nothing
15561557 Just v -> modifyFailure addKeyName
1557− $ Just <$> parseJSON v <?> Key key
1558+ $ parseJSON v <?> Key key
15581559 where
15591560 addKeyName = (("failed to parse field " <> unpack key <> ": ") <>)
15601561{-# INLINE (.:?) #-}
15611562
1563+-- | Like '.:?', but the resulting parser will fail,
1564+-- if the key is present but is 'Null'.
1565+(.:!) :: (FromJSON a) => Object -> Text -> Parser (Maybe a)
1566+obj .:! key = case H.lookup key obj of
1567+ Nothing -> pure Nothing
1568+ Just v -> modifyFailure addKeyName
1569+ $ Just <$> parseJSON v <?> Key key
1570+ where
1571+ addKeyName = (("failed to parse field " <> unpack key <> ": ") <>)
1572+{-# INLINE (.:!) #-}
1573+
15621574-- | Helper for use in combination with '.:?' to provide default
15631575-- values for optional JSON object fields.
15641576--
15651577-- This combinator is most useful if the key and value can be absent
15661578-- from an object without affecting its validity and we know a default
15671579-- value to assign in that case. If the key and value are mandatory,
1568−-- use '(.:)' instead.
1580+-- use '.:' instead.
15691581--
15701582-- Example usage:
15711583--