使用 "lens" 向 JSON 对象添加新字段

Adding a new field to a JSON object with "lens"

请考虑以下方案:

import Control.Monad.Trans.State.Strict
import Control.Lens
import Data.Aeson.Lens
import qualified Data.Aeson


json :: Data.Aeson.Value
json =
  maybe undefined id (Data.Aeson.decode "{\"a\":\"1\"}")

addAField :: State Data.Aeson.Value ()
addAField =
  assign (key "b" . _String) "2"

main =
  print (execState addAField json)

结果如下:

Object (fromList [("a",String "1")])

如何更新 addAField 函数以使程序产生以下输出:

Object (fromList [("a",String "1"), ("b",String "2")])

我能想出的最好办法涉及 JSON 值的直接寻址:

addAField :: State Data.Aeson.Value ()
addAField =
  assign (_Object . at "b") (Just (Data.Aeson.String "2"))