Remove the JSON field from the response when it has an empty value

When the JSON payload has empty values we can remove it from the response payload.

Actual payload

{
“Amount”:”100",
“Currency”:” ”
}

Expected payload
{
“Amount”:”100"
}

We can use one of a method from the following methods to achieve this requirement.

Method 01

  • Here we have used the following Proxy service and the XSLT script to do this.

<proxy xmlns=”http://ws.apache.org/ns/synapse" name=”TestProxy” startOnLoad=”true” statistics=”disable” trace=”disable” transports=”http,https”>
<target>
<inSequence>
<payloadFactory media-type=”json”>
<format>{ “Amount”: “100”, “Currency”: “$1” }</format>
<args>
<arg evaluator=”xml” expression=”//values/currency/text()” />
</args>
</payloadFactory>
<log level=”full” />
<xslt key=”conf:/xslt_test.xslt” />
<respond />
</inSequence>
</target>
<description />
</proxy>

  • Here, I used the XSLT mediator to remove the Currency when the value of the Currency is empty.
  • Following is the XSLT script which used to remove the Currency field.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:es="http://www.abc.com/CDM/ES/">
<xsl:output indent="no"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Currency[not(normalize-space())]"/>
</xsl:stylesheet>
  • We can access the Management_Console->Main Tab->Registry->Browse->/_system/config path and add the script as below.

Method 02

  • We can use the following Proxy service also to remove the Currency when it is empty.

<proxy xmlns=”http://ws.apache.org/ns/synapse" name=”TestProxy” startOnLoad=”true” statistics=”disable” trace=”disable” transports=”http,https”>
<target>
<inSequence>
<payloadFactory media-type=”json”>
<format>{ “Amount”: “100”, “Currency”: “$1” }</format>
<args>
<arg evaluator=”xml” expression=”//values/currency/text()” />
</args>
</payloadFactory>
<log level=”full” />
<script language=”js”>var pl_string = mc.getPayloadJSON();

if (pl_string.Currency == “”){
delete pl_string.Currency;
}
mc.setPayloadJSON(pl_string);</script>
<respond />
</inSequence>
</target>
<description />
</proxy>

The payload which sends with currency is empty

<values>
<currency></currency>
</values>

Curl command which used to invoke the Proxy service

curl -v -X POST -H “Content-Type:application/xml” -d@test.xml “http://localhost:8280/services/TestProxy"

Senior Software Engineer at WSO2