我在 artyom.me/aeson 上找到了以下解决方案来解决我的问题。然而,对于向
toJSON
结果添加单个键的任务来说,它看起来有点臃肿。难道没有更简单的解决方案吗?
instance ToJSON RussianName where
toJSON RussianName{..} = Object $
toObject russianName <>
fromList ["patronymic" .= russianPatronymic]
toObject :: ToJSON a => a -> Object
toObject a = case toJSON a of
Object o -> o
_ -> error "toObject: value isn't an Object"
至少还需要
import Data.Aeson
import Data.Monoid ((<>))
import GHC.Exts (fromList)
我不需要额外的库就可以做到这一点:
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KeyMap
addFieldToJSON :: Text -> Value -> Value -> Value
addFieldToJSON field val = \case
Object obj -> Object (KeyMap.insert (Key.fromText field) val obj)
otherJson -> otherJson
使用示例:
addFieldToJSON "newField" newValue oldJSON
希望有用!