Haskell 如何更新JSON对象的字段?
我正在使用Haskell 如何更新JSON对象的字段?,haskell,aeson,Haskell,Aeson,我正在使用aeson创建一个JSON对象。如何将字段“email”添加到对象 > import Data.Aeson > let alice = object ["name" .= "Alice", "age" .= 20] 我试图使用,但没有成功 > import Data.Monoid > alice <> object ["email" .= "alice@example.org"] <interactive>:12:1: error:
aeson
创建一个JSON对象。如何将字段“email”添加到对象
> 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"]
>导入数据.Monoid
>alice对象[“电子邮件”。=”alice@example.org"]
:12:1:错误:
•没有因使用“”而产生的(幺半群值)实例
•在表达式中:
alice对象[“电子邮件”。=”alice@example.org"]
在“it”的方程式中:
它=alice对象[“电子邮件”。=”alice@example.org"]
在我以前的项目中,我曾经做过这样的事情:
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
使其工作的关键是理解类型值是如何定义的:之所以
不起作用,是因为没有明显的方法组合两个任意JSON值。对于已知为对象或数组的对象,组合起来很简单。但是由于alice::Value
,您丢失了它是对象的信息,并且无法定义()::Value->Value->Value
。