简体   繁体   English

如何合并Aeson对象?

[英]How to merge Aeson objects?

I have a list of aeson objects like this 我有一个像这样的aeson对象列表

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

and I want to merge them as a single aeson object like this 我想将它们合并为像这样的单个aeson对象

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. 当使用其他语言的JSON数据(合并操作)时,这是非常标准的,但我在Aeson库中看不到任何类似的东西。

Am I just missing something and can this be done with some standard haskell function? 我只是遗漏了一些东西,可以用一些标准的haskell功能来完成吗? I tried using sequence but it seems that JSON Value is not a monad so I cannot do that. 我尝试使用sequence但似乎JSON Value不是monad所以我不能这样做。

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 }]

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: 鉴于列表包含JSON对象(因此具有键值对的元素或具有Object构造函数的元素),您可以编写自己的:

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")])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM