3

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 ()
"[]"
4

1 回答 1

7

ToJSON实例()定义为:

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

因为通常,元组被编码为数组:

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

(我认为null没有多大意义;通常表示可能null存在价值的缺乏价值,因此在 Haskell 中您会使用. 实际上,返回.只是一个 0 元组,并且此实例与其他实例更一致元组。)Nothingencode Nothing"null"()

于 2013-10-20T17:43:56.443 回答