Search code examples
jsonhaskellaesonto-json

How to merge Aeson objects?


I have a list of aeson objects like this

[object ["key1" .= "value1"], object ["key2" .= "value2"]] 

and I want to merge them as a single aeson object like this

object ["key1" .= "value1", "key2" .= "value2"]

This is quite standard when working with JSON data in other languages (merge operation) but I don't see anything similar in the Aeson library.

Am I just missing something and can this be done with some standard haskell function? I tried using sequence but it seems that JSON Value is not a monad so I cannot do that.

I don't need to deal with deep merging or duplicate keys, I just want to generate something like

{
  "key1": value1,
  "key2": value2
}

from

[{ "key1": value1 }, { "key2": value2 }]

Solution

  • Given the list contains only of JSON objects (thus elements that have key-value pairs or elements with the Object constructor), you can write your own:

    import Data.Aeson(Value(Object))
    import qualified Data.HashMap.Lazy as HML
    
    merge_aeson :: [Value] -> Value
    merge_aeson = Object . HML.unions . map (\(Object x) -> x)
    

    If we test the above function with the given sample input, we obtain:

    Prelude Data.Aeson HML> merge_aeson [object ["key1" .= "value1"], object ["key2" .= "value2"]] 
    Object (fromList [("key2",String "value2"),("key1",String "value1")])