on master help sign in
Merge pull request #38 from zhensydow/master

Added new accessor with default value

commit8d8d8abe067f4957faa52956881376464567c9e3 authorBryan O'Sullivan <bos@serpentine.com> dateThu 17 Nov 2011, 12:01 (15 years ago) parent2b64dbfd2e9655
3 files changed+17
Data/Aeson.hs+1 Data/Aeson/Types.hs+1 Data/Aeson/Types/Class.hs+15
Data/Aeson.hs+1
@@ -30,6 +30,7 @@ module Data.Aeson
3030 , (.=)
3131 , (.:)
3232 , (.:?)
33+ , (.:/)
3334 , object
3435 -- * Parsing
3536 , json
Data/Aeson/Types.hs+1
@@ -35,6 +35,7 @@ module Data.Aeson.Types
3535 , (.=)
3636 , (.:)
3737 , (.:?)
38+ , (.:/)
3839 , object
3940 ) where
4041
Data/Aeson/Types/Class.hs+15
@@ -33,6 +33,7 @@ module Data.Aeson.Types.Class
3333 , fromJSON
3434 , (.:)
3535 , (.:?)
36+ , (.:/)
3637 , (.=)
3738 , typeMismatch
3839 ) where
@@ -706,6 +707,20 @@ obj .:? key = case H.lookup key obj of
706707 Just v -> parseJSON v
707708{-# INLINE (.:?) #-}
708709
710+-- | Retrieve the value associated with the given key of an 'Object'.
711+-- The result is a default value if the key is not present, or 'empty'
712+-- if the value cannot be converted to the desired type.
713+--
714+-- This accessor is most useful if the key and value can be absent
715+-- from an object without affecting its validity and we know a
716+-- default value to assign in that case. If the key and value
717+-- are mandatory, use '(.:)' instead.
718+(.:/) :: (FromJSON a) => Object -> (Text, a) -> Parser a
719+obj .:/ (key, val) = case M.lookup key obj of
720+ Nothing -> pure val
721+ Just v -> parseJSON v
722+{-# INLINE (.:/) #-}
723+
709724
710725-- | Fail parsing due to a type mismatch, with a descriptive message.
711726typeMismatch :: String -- ^ The name of the type you are trying to parse.