Haskell Aeson return 空对象

Haskell Aeson return empty object

我正在尝试 return 如果不是 Nothing,则 JSON 数据表示,如果 Nothing,则为空的 JSON 对象;

我知道我能做到:

encode ()
-- "[]"

但现在我想要一个空对象 ("{}")。

我有这个,它可以根据给定的字段生成 JSON:

λ data Person = Person { id :: Integer, height :: Float } deriving (Show)
λ instance ToJSON Person where toJSON (Person { id = id, height = height }) = object [ "id" .= id, "height" .= height ]
λ encode (Person 1 72.8)
-- "{\"height\":72.8,\"id\":1}"

但最终没有人会用 Nothing 表示,如果我这样做 encode (Nothing) 我会得到一个错误:

<interactive>:11:1: error:
    • Ambiguous type variable ‘a0’ arising from a use of ‘encode’
      prevents the constraint ‘(ToJSON a0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘a0’ should be.
      These potential instances exist:
        instance ToJSON DotNetTime
          -- Defined in ‘aeson-1.4.7.1:Data.Aeson.Types.ToJSON’
        instance ToJSON Value
          -- Defined in ‘aeson-1.4.7.1:Data.Aeson.Types.ToJSON’
        instance (ToJSON a, ToJSON b) => ToJSON (Either a b)
          -- Defined in ‘aeson-1.4.7.1:Data.Aeson.Types.ToJSON’
        ...plus 26 others
        ...plus 63 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the expression: encode (Nothing)
      In an equation for ‘it’: it = encode (Nothing)

encode Nothing 将始终 return null。可以通过 encode (object []) 对空对象进行编码。如果您想以这种方式编码 Nothings,您可以为 Maybe 值编写自定义编码函数,如下所示。

encodeMaybe :: ToJSON a => Maybe a -> ByteString
encodeMaybe (Just x) = encode x
encodeMaybe Nothing  = encode (object [])

或者

toJSONMaybe :: ToJSON a => Maybe a -> Value
toJSONMaybe (Just x) = toJSON x
toJSONMaybe Nothing  = object []