Leo Zhang
Leo Zhang

Reputation: 3240

How to update a field of a JSON object?

I'm creating an object as JSON using aeson. How to add a field "email" to the object?

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

I tried to use <> but didn't work

> import Data.Monoid
> alice <> object ["email" .= "[email protected]"]

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

Upvotes: 3

Views: 576

Answers (1)

Sibi
Sibi

Reputation: 48766

In my previous project, I used to do something like this:

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

And then on ghci:

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

The key on making it work is understanding how the type Value is defined: https://www.stackage.org/haddock/lts-12.1/aeson-1.3.1.1/Data-Aeson.html#t:Value

Upvotes: 3

Related Questions