Haskell Aeson 返回空对象

标签 haskell ihp

如果不是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}"
但最终,如果我这样做,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)

最佳答案

encode Nothing将永远返回 null .可以通过执行 encode (object []) 来对空对象进行编码。 .如果你想编码 Nothings这样,您可以为 Maybe 编写自定义编码函数。这样的值(value)观。

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 []

关于Haskell Aeson 返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65952459/

相关文章:

haskell - IHP:如何使用其他字段的值验证字段

haskell - 分解出 Controller Action

haskell - 如何使用 haskell 和 stack 在 gitpod 上进行预构建

function - Haskell 在数据结构中存储函数 - 用例

IHP - 如何在操作结束时编写自定义响应?

ihp - 知道为什么 Cachix 无法在 macOS 上运行吗?

haskell - 如何更改 IHP 应用程序中的 &lt;title&gt;?

Haskell 浮点精度

data-structures - 使用 VLists 的哈希表

haskell - 使用 Haskell 中的代码进行类似 Lisp 的配置