Search code examples
dataweavemulesoftmule4

How to remove trailing comma from a object inside a json array using dataweave?


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.


Solution

  • 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