首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Haskell Aeson返回空对象

Haskell Aeson返回空对象
EN

Stack Overflow用户
提问于 2021-01-29 18:10:28
回答 1查看 160关注 0票数 3

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

我知道我可以做到:

代码语言:javascript
复制
encode ()
-- "[]"

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

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

代码语言:javascript
复制
λ 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}"

但最终一个人的缺席将被表示为没有任何东西,如果我执行encode (Nothing),我会得到一个错误:

代码语言:javascript
复制
<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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-29 19:21:58

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

代码语言:javascript
复制
encodeMaybe :: ToJSON a => Maybe a -> ByteString
encodeMaybe (Just x) = encode x
encodeMaybe Nothing  = encode (object [])

或者另选地

代码语言:javascript
复制
toJSONMaybe :: ToJSON a => Maybe a -> Value
toJSONMaybe (Just x) = toJSON x
toJSONMaybe Nothing  = object []
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65952459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档