Commits

jsgf committed c4b24ee

Add Missing Value for non-present values.

If a Maybe a value should only be optionally included in an Object (as
opposed to being set as "null"), then use .=? to construct its Pair.
This sets the Value to Missing, which causes it to be subsequently
excluded from the Object.

Comments (0)

Files changed (3)

     , ToJSON(..)
     -- * Constructors and accessors
     , (.=)
+    , (.=?)
     , (.:)
     , (.:?)
     , object

Data/Aeson/Encode.hs

 -- | Encode a JSON value to a 'Builder'.
 fromValue :: Value -> Builder
 fromValue Null = fromByteString "null"
+fromValue Missing = error "Unexpected Missing"
 fromValue (Bool b) = fromByteString $ if b then "true" else "false"
 fromValue (Number n) = fromByteString (B.pack (show n))
 fromValue (String s) = string s

Data/Aeson/Types.hs

     , ToJSON(..)
     -- * Constructors and accessors
     , (.=)
+    , (.=?)
     , (.:)
     , (.:?)
     , object
            | Number Number
            | Bool !Bool
            | Null
+           | Missing
              deriving (Eq, Show, Typeable, Data)
 
 instance NFData Value where
     rnf (Number n) = case n of I i -> rnf i; D d -> rnf d
     rnf (Bool b)   = rnf b
     rnf Null       = ()
+    rnf Missing    = ()
 
 -- | The empty array.
 emptyArray :: Value
 name .= value = (name, toJSON value)
 {-# INLINE (.=) #-}
 
+-- | Construct an optional 'Pair' from a key and a Maybe value.  If
+-- the value is Nothing, then it is omitted altogether from the
+-- resulting Object.
+(.=?) :: ToJSON a => Text -> Maybe a -> Pair
+name .=? Nothing    = (name, Missing)
+name .=? Just value = (name, toJSON value)
+{-# INLINE (.=?) #-}
+
 -- | Convert a value from JSON, failing if the types do not match.
 fromJSON :: (FromJSON a) => Value -> Result a
 fromJSON = parse parseJSON
 -- | Create a 'Value' from a list of name\/value 'Pair's.  If duplicate
 -- keys arise, earlier keys and their associated values win.
 object :: [Pair] -> Value
-object = Object . M.fromList
+object = Object . M.fromList . filter (notmissing . snd) 
+    where notmissing Missing = False
+          notmissing _       = True
 {-# INLINE object #-}
 
 -- | A type that can be converted to JSON.