Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Aeson encodes () as empty array?

I am surprised to know that Aeson encodes () as empty array. What is reason behind such behaviour? I think null would be more natural, am I wrong?

*Main> encode ()
"[]"
like image 365
lambdas Avatar asked Dec 13 '25 03:12

lambdas


1 Answers

The ToJSON instance for () is defined as:

instance ToJSON () where
    toJSON _ = emptyArray
    {-# INLINE toJSON #-}

Because generally, tuples are encoded as arrays:

instance (ToJSON a, ToJSON b) => ToJSON (a,b) where
    toJSON (a,b) = Array $ V.create $ do
                     mv <- VM.unsafeNew 2
                     VM.unsafeWrite mv 0 (toJSON a)
                     VM.unsafeWrite mv 1 (toJSON b)
                     return mv

(I think null doesn't make much sense; usually null represents a lack of value where there could be one, so in Haskell you'd use Nothing. In fact, encode Nothing returns "null". () is just a 0-tuple, and this instance is more consistent with other tuples.)

like image 166
Lynn Avatar answered Dec 15 '25 17:12

Lynn