Question

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 ()
"[]"
Was it helpful?

Solution

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.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top