You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mule中将输入JSON数组转换为指定格式的CSV?

Solution for JSON Array to Custom Formatted String in Mule

Got it, let's tackle this custom conversion in Mule using DataWeave 2.0—this is the standard tool for transformations in Mule 4+, and it'll handle this perfectly. Here's a step-by-step breakdown and working script:

Step 1: Group Data by Gender

First, we'll group your input JSON array using the gender field. This lets us bundle all "F" and "M" entries separately, which aligns with your desired output structure.

Step 2: Format Segments and Combine

Next, we'll format each group into the required string chunks, then stitch everything together with your specified delimiter **|**.

Full DataWeave Script

%dw 2.0
output application/text
var groupedData = payload groupBy $.gender
// Define group order to match your expected output (F first, then M)
var groupOrder = ["F", "M"]
---
groupOrder flatMap (gender) -> do {
    // Sort entries by ID descending to match your sample output order
    var sortedEntries = groupedData[gender] orderBy -$.id
    var formattedEntries = sortedEntries map ("$(name)*$(id)")
    // Combine gender header with formatted entries
    ["gender:$(gender)"] ++ formattedEntries
} joinBy "**|**" ++ "**|**"

Test with Your Input

When you feed your input JSON array:

[ 
  { "id":"001", "name":"john", "gender": "M" }, 
  { "id":"002", "name":"Mule", "gender": "F" }, 
  { "id":"003", "name":"Sara", "gender": "F" }, 
  { "id":"004", "name":"Mati", "gender": "F" } 
]

You'll get exactly the output you're expecting:

gender:F**|**Mati*004**|**Sara*003**|**Mule*002**|**gender:M**|**john*001**|**

How It Works

  • groupBy $.gender: Groups the input into an object where keys are "F"/"M" and values are the matching entry arrays.
  • groupOrder: Forces us to process "F" entries first, then "M" to match your output sequence.
  • orderBy -$.id: Sorts entries within each group by ID descending, which gives you the "Mati004" → "Sara003" → "Mule*002" order from your sample.
  • flatMap: Builds the header string for each group, then maps every entry to the "name*id" format.
  • joinBy "**|**": Glues all segments together with your delimiter.
  • ++ "**|**": Adds the trailing delimiter as seen in your desired output.

If you need to adjust the entry order (e.g., sort by name instead of ID), just modify the orderBy clause—swap -$.id with $.name to sort alphabetically, for example.

内容的提问来源于stack exchange,提问作者Amira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:05:48