Anonymous avatar Anonymous committed ca1d23b

Add `.!=` operator as a ternary-style operator alternative to '.:/'

See haddock comment for usage example

Comments (0)

Files changed (3)

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

Data/Aeson/Types.hs

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

Data/Aeson/Types/Class.hs

     , fromJSON
     , (.:)
     , (.:?)
+    , (.!=)
     , (.:/)
     , (.=)
     , typeMismatch
 import Data.Attoparsec.Char8 (Number(..))
 import Data.Hashable (Hashable(..))
 import Data.Int (Int8, Int16, Int32, Int64)
+import Data.Maybe (fromMaybe)
 import Data.Monoid (Dual(..), First(..), Last(..))
 import Data.Ratio (Ratio)
 import Data.Text (Text, pack, unpack)
                Just v  -> parseJSON v
 {-# INLINE (.:?) #-}
 
+-- | Helper for use in combination with '.:?' to provide default
+-- values for optional JSON object fields.
+-- 
+-- Example usage:
+--
+-- @ v1 <- o '.:?' \"opt_field_with_dfl\" .!= \"default_val\"
+-- v2 <- o '.:'  \"mandatory_field\"
+-- v3 <- o '.:?' \"opt_field2\"
+--
+-- \-- alternative version of v1 using the '.:/' operator
+-- v1' <- o '.:/' (\"opt_field_with_dfl\", \"default_val\")
+-- @
+(.!=) :: Parser (Maybe a) -> a -> Parser a
+pmval .!= val = fromMaybe val <$> pmval
+{-# 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.
 -- 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.
+--
+-- See also '.!=' for an alternative way to represent optional fields
+-- with defaulting.
 (.:/) :: (FromJSON a) => Object -> (Text, a) -> Parser a
 obj .:/ (key, val) = case H.lookup key obj of
                        Nothing -> pure val
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.