如何更新JSON对象的字段?

时间:2018-07-18 17:09:53

标签: haskell aeson

我正在使用aeson将对象创建为JSON。如何向对象添加字段“电子邮件”?

> import Data.Aeson
> let alice = object ["name" .= "Alice", "age" .= 20]

我尝试使用<>,但没有用

> import Data.Monoid
> alice <> object ["email" .= "alice@example.org"]

<interactive>:12:1: error:
    • No instance for (Monoid Value) arising from a use of ‘<>’
    • In the expression:
        alice <> object ["email" .= "alice@example.org"]
      In an equation for ‘it’:
          it = alice <> object ["email" .= "alice@example.org"]

1 个答案:

答案 0 :(得分:2)

在上一个项目中,我曾经做过这样的事情:

import Data.Aeson
import Data.Text
import qualified Data.HashMap.Strict as HM

addJsonKey :: Text -> Value -> Value -> Value
addJsonKey key val (Object xs) = Object $ HM.insert key val xs
addJsonKey _ _ xs = xs

然后在ghci上

λ> :set -XOverloadedStrings
λ> let alice = object ["name" .= "Alice", "age" .= 20]
λ> addJsonKey "email" (String "sibi@psibi.in") alice

使其工作的关键是了解如何定义Value类型:https://www.stackage.org/haddock/lts-12.1/aeson-1.3.1.1/Data-Aeson.html#t:Value