How to replace the payload from json object in mule

1.7k Views Asked by At

Prepared json request like below.

[{
    "type": "John",
    "attributes": {
        "AA": [{
            "value": "1234"
        }]
    }
}, 
{

}
]

I need to replace the below one with empty i.e means blank ''.

, 
    {

    }

Could you please provide the solution for this.

Finally It should come like below.

[{
        "type": "John",
        "attributes": {
            "AA": [{
                "value": "1234"
            }]
        }
    }
]
4

There are 4 best solutions below

3
On

This regex matches the given sequence however you would probably need to change it to accept all possibilities:

/, \n\{\W+?\}/

Just replace the match with nothing.

2
On

Do you get the response as a JSON object or as a string?

If you get the response as an object you have to stringify it before applying the replace function:

payload = JSON.parse(JSON.stringify(payload).replace(/,\{\}/, ''))

If the response you posted above is already stringified and you haven´t parsed it into an object, the method is:

payload = payload.replace(/\,\s+\n\s+\{\n\s+\}/,'')
2
On

To achieve this purpose, we can use DataWeave expression whether in Transform Message or in MEL.

In this case I prefer to use it in MEL: #[dw('payload filter (sizeOf $) > 0')]

0
On

You can use the flatten operator here as given below. It should remove empty json. Also you can try replace {} with null and adding skipnullon="everywhere"

flatten payload