如何在DataWeave中将Java LinkedHashMap条目转换为对象数组
Let's break down what's happening here and fix the output to match exactly what you need.
First, let's clarify the core details:
- Input: A Java
LinkedHashMapwith a single entry:{ target: "test-app-387562893" } - Desired Output: An array containing that entry as a standalone object:
[ { target: "test-app-387562893" } ]
Why Your Current Code Isn't Giving the Exact Output You Want
Your existing pluck code:
%dw 2.0 output application/java --- payload pluck (value,key) -> { (key): value }
...actually returns a single object ({ target: "test-app-387562893" }) when given a single-entry LinkedHashMap, not an array. It sounds like you might be seeing this object wrapped in an array unintentionally elsewhere, or perhaps you just need to explicitly structure the output as an array. Let's adjust the code to get the exact format you need.
Fix 1: Wrap the Pluck Result in an Array
If you want to take every key-value pair in your LinkedHashMap, convert each to a standalone object, and wrap all of them in an array, simply enclose the pluck expression in square brackets:
%dw 2.0 output application/java --- [ payload pluck (value, key) -> { (key): value } ]
For your single-entry input, this will output exactly [ { target: "test-app-387562893" } ]. If your LinkedHashMap had multiple entries (e.g., { app1: "test1", app2: "test2" }), this would return [ { app1: "test1" }, { app2: "test2" } ]—perfect for turning each map entry into an array element.
Fix 2: Extract Values Directly (If Your Map Values Are Already Objects)
If your LinkedHashMap's values are already the objects you want in the array (e.g., input is { "entry1": { target: "test-app-387562893" } }), you don't need to rebuild the object with the key. Instead, just pluck the values directly using the shorthand $:
%dw 2.0 output application/java --- payload pluck $
This will extract all values from the map and place them into an array. For your example input, this gives you [ { target: "test-app-387562893" } ] directly.
Note on Java Output Type
Since you're using output application/java, DataWeave will convert the array to a Java List containing the appropriate objects (in this case, a List with one LinkedHashMap entry, which matches your desired structure).
内容的提问来源于stack exchange,提问作者short stack stevens

