如何用DataWeave将ArrayList转换为含重复键的Object?
Solution to Merge Array of Objects into Single Object with Duplicate Keys
Problem Statement
You have an input payload that's an array of objects:
[{"A":"234"},{"A": "123"}]
And you want to convert it into a single object with duplicate keys (even though this isn't strictly compliant with standard JSON, DataWeave supports generating such output):
{"A":"234", "A": "123"}
DataWeave Script
Here's the script that achieves this:
%dw 2.0 output application/json --- fromEntries(payload flatMap ((item) -> item entries))
How It Works
Let's break down what each part does:
item entries: Converts each object in the input array into an array of key-value pairs. For your input, this turns{"A":"234"}into[("A", "234")]and{"A": "123"}into[("A", "123")].flatMap: Takes all those key-value pair arrays and flattens them into a single array:[("A", "234"), ("A", "123")].fromEntries(...): Converts the flattened key-value pair array back into an object. Unlike regular object merging (which overwrites duplicate keys), this method preserves all entries even when keys are identical.
Note
Keep in mind that while DataWeave can generate objects with duplicate keys, many standard JSON parsers will ignore or overwrite duplicate keys when parsing the output. This works best if your downstream system explicitly supports handling duplicate keys in JSON.
内容的提问来源于stack exchange,提问作者Hemant
相关产品推荐
相关产品推荐

