Home > other >  XSLT 3.0 - Not able to get Array of objects in XSLT 3.0 xml-to-json()
XSLT 3.0 - Not able to get Array of objects in XSLT 3.0 xml-to-json()

Time:09-16

I am trying to convert given json data from one form to another using XSLT 3.0. I am using json-to-xml and xml-to-json functions provides by XSLT 3.0 to convert data from.to json to/from xml .

I am having below json data.

 {
   "id": "123456",
   "result": "Success"
  }

I am trying to convert it to below form using XSLT 3.0

[
  {
   "key":"id",
   "value":"123456"
  },
  {
    "key":"result",
    "value":"Success"
   }
 ]

I am having below XSLT.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  version="3.0"
  xmlns="http://www.w3.org/2005/xpath-functions"
  xpath-default-namespace="http://www.w3.org/2005/xpath-functions"
  expand-text="yes">
  <xsl:param name="json"/>

  <xsl:output method="text"/>


   <xsl:mode on-no-match="shallow-skip"/>

   <xsl:template match="/" name="init">
    <xsl:variable name="json-xml" select="json-to-xml($json)"/>
    <xsl:variable name="transformed-json-xml">
     <map>
      <xsl:apply-templates select="$json-xml//map"/>
     </map>
    </xsl:variable>
    <xsl:value-of select="xml-to-json($transformed-json-xml, map { 'indent' : true() })"/>
   </xsl:template>

    <xsl:template match="map[string[@key = 'id'] and string[@key = 'result']]">
    <string key="key">id</string>
    <string key="value">{string[@key = 'id']}</string>
    </xsl:template>

   </xsl:stylesheet>

But its producing only one object

 { "key" : "id",
"value" : "123456" }

Can anyone point where i need to make changes?

CodePudding user response:

Well, if you want an array as the outer JSON structure you need to change

<xsl:variable name="transformed-json-xml">
 <map>
  <xsl:apply-templates select="$json-xml//map"/>
 </map>

to

<xsl:variable name="transformed-json-xml">
 <array>
  <xsl:apply-templates select="$json-xml//map"/>
 </array>

For your map you want

<xsl:template match="map[string[@key = 'id'] and string[@key = 'result']]">
  <xsl:apply-templates/>
</xsl:template>

plus

  <xsl:template match="string">
    <map>
      <string key="key">{@key}</string>
      <string key="value">{.}</string>
    </map>
  </xsl:template>
  • Related