JSON to XSLT : default XML node if JSON element does NOT exist

I have json structured like:

{
  "Message" :
  {
    "dynamicFields" :
    [ {
      "alias" : "TEST_ALIAS",
      "value" : "VALUE"
      }
      ,
      {
      "alias" : "CAR",
      "value" : "TOYOTA"
      }
    ]
  }
}

I have an xslt stylesheet set up like:

    <xsl:template match="j:map[j:string[@key='value' and text() !='']]">

        <xsl:if test="j:string[@key='alias' and text() != '']">
            
           <ns2:field name="{j:string[@key='alias']}">
                
               <xsl:value-of select="upper-case(j:string[@key='value'])"/>
            
           </ns2:field>
        
        </xsl:if>

    </xsl:template>

Which creates elements like:

 <ns2:field name="TEST_ALIAS">VALUE</ns2:field>

But I can't figure out how to add xml nodes conditionally

For example, if there doesn't exist a JSON element with an alias of CAR, add it with a default value

So basically, if the JSON looked like:

{
  "Message" :
  {
    "dynamicFields" :
    [ {
      "alias" : "TEST_ALIAS",
      "value" : "VALUE"
      }
    ]
  }
}

The xml would look like:

 <ns2:field name="TEST_ALIAS">VALUE</ns2:field>
 <ns2:field name="CAR">DEFAULT_CAR_VALUE</ns2:field>

the only assumption i can make about the JSON is that there will be elements with both an alias key and a value key


Without seeing a complete XSLT, I'm taking a bit of a guess, but I think you could add(or modify) the template for the dynamicFields property and inside of that add a test to see whether the array contains an object that has an alias of "CAR", and if not, add the default <ns2:field name="CAR"> DEFAULT_CAR_VALUE</ns2:field> element:

<xsl:template match="j:array[@key='dynamicFields']">
    <xsl:apply-templates />
    <xsl:variable name="default-field" select="'CAR'"/>
    <xsl:if test="not(j:map/j:string[@key='alias'] = $default-field)">
        <ns2:field name="{$default-field}">
            <xsl:text>DEFAULT_CAR_VALUE</xsl:text>
        </ns2:field>  
    </xsl:if>
</xsl:template>    

<xsl:template match="j:map[j:string[@key='value' and text() !='']]">
    <xsl:if test="j:string[@key='alias' and text() != '']">
        <ns2:field name="{j:string[@key='alias']}">
            <xsl:value-of select="upper-case(j:string[@key='value'])"/>
        </ns2:field>        
    </xsl:if>    
</xsl:template>