Reputation: 27
How to remove trailing commas from each line of the object inside the json array? sample input:
[
{
"dc": "cn=Cggzci,dc=maxcrc,dc=com",
"objectClass": "top",
"objectClass": "person",
"cn": "Cggzci",
"sn": "Mqemdv"
},
{
"dc": "cn=Vntlww,dc=maxcrc,dc=com",
"objectClass": "top",
"objectClass": "person",
"cn": "Vntlww",
"sn": "Fehiqr"
}
]
Dataweave:
%dw 2.0
output text/plain
var test = (write(payload,'application/json'))
---
test replace /\[\n|\n\]|\{|\},\n|\}|"/ with ""
Output received:
dc: cn=Cggzci,dc=maxcrc,dc=com,
objectClass: top,
objectClass: person,
cn: Cggzci,
sn: Mqemdv
dc: cn=Vntlww,dc=maxcrc,dc=com,
objectClass: top,
objectClass: person,
cn: Vntlww,
sn: Fehiqr
Require output should be without trailing commas in each line and remove spaces beginning each line.
Upvotes: 1
Views: 248
Reputation: 25837
I recommend to avoid regular expressions for things like this. It is simpler to transform the structure of the data.
This solution assumes that the structure is a list of objects. It makes no assumptions on the structure of each object.
%dw 2.0
output text/plain
fun printRecord(x)=x pluck ($$ as String ++ ": " ++ $) joinBy "\n"
---
payload map printRecord($) joinBy "\n\n"
Output:
dc: cn=Cggzci,dc=maxcrc,dc=com
objectClass: top
objectClass: person
cn: Cggzci
sn: Mqemdv
dc: cn=Vntlww,dc=maxcrc,dc=com
objectClass: top
objectClass: person
cn: Vntlww
sn: Fehiqr
Upvotes: 3
Reputation: 5059
The best way to implement your ask is not by doing replace but by handling the data structure and generating your output
%dw 2.0
output text/plain
fun toFlat(value: Array<Object>): String =
value map ((item, index) -> toFlat(item))
joinBy "\n\n"
fun toFlat(value: Object) : String =
value pluck ((value, key, index) -> "$(key): $(value as String)")
joinBy "\n"
---
toFlat(payload)
This will output what you want and doesn't depend on your input values but rather on your input shape an Array of Objects
Upvotes: 3