Haskell Aeson 返回空对象

seb*_*seb 3 haskell ihp

如果不是Nothing,我试图返回一个JSON数据表示,如果Nothing则返回一个空的JSON对象;

我知道我可以做到:

encode ()
-- "[]"
Run Code Online (Sandbox Code Playgroud)

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

我有这个,它可以根据给定的字段生成 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}"
Run Code Online (Sandbox Code Playgroud)

但最终没有 Person 将用 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)
Run Code Online (Sandbox Code Playgroud)

小智 5

encode Nothing总会回来的null。编码一个空对象可以通过执行encode (object []). 如果你想以Nothings这种方式编码,你可以为这样的Maybe值编写一个自定义编码函数。

encodeMaybe :: ToJSON a => Maybe a -> ByteString
encodeMaybe (Just x) = encode x
encodeMaybe Nothing  = encode (object [])
Run Code Online (Sandbox Code Playgroud)

或者替代地

toJSONMaybe :: ToJSON a => Maybe a -> Value
toJSONMaybe (Just x) = toJSON x
toJSONMaybe Nothing  = object []
Run Code Online (Sandbox Code Playgroud)