Commits

Bryan O'Sullivan committed cb5d426 Merge

Merge pull request #38 from zhensydow/master

Added new accessor with default value

  • Participants
  • Parent commits 57d02db, d77e0a7

Comments (0)

Files changed (3)

     , (.=)
     , (.:)
     , (.:?)
+    , (.:/)
     , object
     -- * Parsing
     , json

Data/Aeson/Types.hs

     , (.=)
     , (.:)
     , (.:?)
+    , (.:/)
     , object
     ) where
 

Data/Aeson/Types/Class.hs

     , fromJSON
     , (.:)
     , (.:?)
+    , (.:/)
     , (.=)
     , typeMismatch
     ) where
                Just v  -> parseJSON v
 {-# INLINE (.:?) #-}
 
+-- | Retrieve the value associated with the given key of an 'Object'.
+-- The result is a default value if the key is not present, or 'empty' 
+-- if the value cannot be converted to the desired type.
+--
+-- This accessor is most useful if the key and value can be absent 
+-- from an object without affecting its validity and we know a 
+-- default value to assign in that case.  If the key and value 
+-- are mandatory, use '(.:)' instead.
+(.:/) :: (FromJSON a) => Object -> (Text, a) -> Parser a
+obj .:/ (key, val) = case M.lookup key obj of
+               Nothing -> pure val
+               Just v  -> parseJSON v
+{-# INLINE (.:/) #-}
+
 
 -- | Fail parsing due to a type mismatch, with a descriptive message.
 typeMismatch :: String -- ^ The name of the type you are trying to parse.