我正在使用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"]
答案 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