如何更新 JSON 对象的字段?
How to update a field of a JSON object?
我正在使用 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"]
在我之前的项目中,我曾经做过这样的事情:
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
我正在使用 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"]
在我之前的项目中,我曾经做过这样的事情:
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