在 Mule 中合并 JSON

Merge JSON in Mule

我有一个 JSON 数组,里面有两个元素。我想将它们合并为一个json。我怎样才能在 Mule 中做到这一点?

原始有效负载:

[{
    "Response1": {
        "lines": [{
            "lineIdentifier": 9,
            "result1": null
        }]
    }
}, {
    "Response2": {
        "lines": [{
            "lineIdentifier": 10,
            "result2": ".0225"
        }]
    }
}]

预期有效负载:

{
    "Response1": {
        "lines": [{
            "lineIdentifier": 9,
            "result1": null
        }]
    },
    "Response2": {
        "lines": [{
            "lineIdentifier": 10,
            "result2": ".0225"
        }]
    }
} 

可以用dataweave来实现,下面是实现逻辑。

 %dw 1.0
%var input=[{
    "Response1": {
        "lines": [{
            "lineIdentifier": 9,
            "result1": null
        }]
    }
}, {
    "Response2": {
        "lines": [{
            "lineIdentifier": 10,
            "result2": ".0225"
        }]
    }
}]
%output application/json
---
{
    "Response1":input[0].Response1,
    "Response2": input[1].Response2
}

只能使用 dataweave 完成

%dw 1.0
%output application/json
---
{
    "Response1" : {
        (payload.Response1.lines map ((item, indexOfItem) -> {
            "lines": item
        })
    )
    },
    "Response2" : {
        (payload.Response2.lines map ((item, indexOfItem) -> {
            "lines": item
        })
    )
    }
}
var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);

使用 reduce 运算符的最简单方法,这样您就不必担心对象的数量。请尝试以下代码

%dw 1.0
%output application/json
---
payload reduce ((value, accumulator = {}) -> accumulator ++ value)

HTH

抱歉,我相信您正在朝着错误的目标前进。 您提供的简单示例误导了简单的答案。

让我解释一下你的问题:

我们有数组 [a,b,c,...x,y,z]

我们需要将它合并到一个对象中{a1:a, b2:b, c3:c,... z26:z }

您只提供了 2 件商品,但就是这样。如果您真的只想要这些特定项目,请使用任何其他答案。但是,如果我是对的,并且您总体上想要它,那么即使它可以通过多种方式完成,请考虑此解决方案的缺点:

  • 对于像 a1、b2、x26 这样的实际键,代码将是 "harcdoded"
  • 模块结构将是 "hardwired" 键和数据
  • 对于一个特定的数据集
  • ,整个解决方案将是"hardprinted"

因此,一般来说,当它几乎不依赖于您的数据时,这不是一个好的解决方案。