on master help sign in
add new accessor (.:/) to allow default value
d2e9655Luis Cabellos
Data/Aeson.hs+1
@@ -30,6 +30,7 @@ module Data.Aeson
30 , (.=)
30 , (.=)
31 , (.:)
31 , (.:)
32 , (.:?)
32 , (.:?)
33+ , (.:/)
33 , object
34 , object
34 -- * Parsing
35 -- * Parsing
35 , json
36 , json
Data/Aeson/Types.hs+1
@@ -35,6 +35,7 @@ module Data.Aeson.Types
35 , (.=)
35 , (.=)
36 , (.:)
36 , (.:)
37 , (.:?)
37 , (.:?)
38+ , (.:/)
38 , object
39 , object
39 ) where
40 ) where
40
41
Data/Aeson/Types/Class.hs+15
@@ -33,6 +33,7 @@ module Data.Aeson.Types.Class
33 , fromJSON
33 , fromJSON
34 , (.:)
34 , (.:)
35 , (.:?)
35 , (.:?)
36+ , (.:/)
36 , (.=)
37 , (.=)
37 , typeMismatch
38 , typeMismatch
38 ) where
39 ) where
@@ -707,6 +708,20 @@ obj .:? key = case M.lookup key obj of
707 Just v -> parseJSON v
708 Just v -> parseJSON v
708{-# INLINE (.:?) #-}
709{-# INLINE (.:?) #-}
709
710
711+-- | Retrieve the value associated with the given key of an 'Object'.
712+-- The result is a default value if the key is not present, or 'empty'
713+-- if the value cannot be converted to the desired type.
714+--
715+-- This accessor is most useful if the key and value can be absent
716+-- from an object without affecting its validity and we know a
717+-- default value to assign in that case. If the key and value
718+-- are mandatory, use '(.:)' instead.
719+(.:/) :: (FromJSON a) => Object -> (Text, a) -> Parser a
720+obj .:/ (key, val) = case M.lookup key obj of
721+ Nothing -> pure val
722+ Just v -> parseJSON v
723+{-# INLINE (.:/) #-}
724+
710
725
711-- | Fail parsing due to a type mismatch, with a descriptive message.
726-- | Fail parsing due to a type mismatch, with a descriptive message.
712typeMismatch :: String -- ^ The name of the type you are trying to parse.
727typeMismatch :: String -- ^ The name of the type you are trying to parse.