I have a JSON request like
{
"aaaa": []
}
First I need to check aaaa exist in my request payload, if exists like as above, I need to add a jsonObject with dummy attributes and values like:
{
"aaaa": [
{
"@c": "test"
"a": "99999",
"b": "test",
"c": "test"
}
],
If aaaa does not exist in my payload, I need to add it with its dummy attributes and values also. So, if the payload is {} , after xslt, it should be the same JSON as above. In my transformation, I tried to handle this problem in this way:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="//jsonObject">
<xsl:copy>
<xsl:if test="//jsonObject/not(aaaa)">
<aaaa>
<xsl:attribute name="c">test</xsl:attribute>
<a>99999</a>
<b>test</b>
<c>test</c>
</aaaa>
</xsl:if>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="//jsonObject/aaaa">
<xsl:copy>
<xsl:attribute name="c">test</xsl:attribute>
<a>99999</a>
<b>test</b>
<c>test</c>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
With this request:
{
"aaaa": []
}
I cannot see aaaa array and its dummy attributes after transformation.
Thanks for any advice!
From WSO2 documentation
JSON:
{"array":[]}XML (JsonStreamBuilder):
<jsonObject></jsonObject>XML (JsonBuilder):
<jsonObject> <?xml-multiple array?> </jsonObject>
When I run your transformation with both outputs, I get
<jsonObject>
<aaaa c="test">
<a>99999</a>
<b>test</b>
<c>test</c>
</aaaa>
</jsonObject>
And
<jsonObject>
<aaaa c="test">
<a>99999</a>
<b>test</b>
<c>test</c>
</aaaa>
<?xml-multiple array?>
</jsonObject>
Do note: I'm not saying that I endorse your stylesheet. I would be better using:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="jsonObject[not(aaaa)]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<aaaa c="test">
<a>99999</a>
<b>test</b>
<c>test</c>
</aaaa>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With