0
votes

this is my Json input

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

I need to generate this output

gender:F**|**Mati*004**|**Sara*003**|**
gender:M**|**john*001**|**Mule*002**|**
1
your post is not well formated and thus hard to read. Please editxiawi
Please also post version you are using and have you looked into dataweavefunctions and any effort you have madeVen

1 Answers

1
votes

I have to say that the output doesn't look to be a standard CSV. Having said that, it is possible to achieve the desired output in DataWeave. I'm assuming that your output is incorrect, because the "Mule" record is grouped as Male.

I needed several steps to achieve the result. First to group the records by gender using groupBy(). Then using pluck() to create an array with the output of the groupBy(), to be able to map it. Then using reduce to create a single line string for each group. Perhaps there is a simpler way to get the same result, however the expected output is not a natural match for the CSV format, so everything has to be done manually. If possible I would suggest to use a simpler output format.

This is the resulting script:

%dw 2.0
output application/csv header=false
---
(payload groupBy (item) -> item.gender  )
     pluck ((value, key, index) -> {
        k: key,
        v: value
     }
    ) map ((it, in) -> {
        record: "gender:" ++ it.k  ++ (it.v reduce ((person, acc="") -> acc ++ "**|**" ++ person.name ++ "*" ++ person.id) ++  "**|**")
    }
)

Which gives this output for your input:

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