Kevin Mbugua
Kevin Mbugua

Reputation: 375

Using XSLT to transform XML to JSON and add Square bracket [] to the JSON

Am trying to enclose/add square brackets to Json after using XSLT for conversion. I want the Json to be in a list/array form.

Below is my XML file.

<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <string key="foedselsdato">2019-04-22</string>
   <string key="individId">01387</string>
   <map key="varslinger"/>
</map>

This is my XSL file below.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">
  <xsl:output omit-xml-declaration="yes"/>
  <xsl:template match="/">
      <xsl:value-of select="xml-to-json(., map { 'indent' : true() })"/>
  </xsl:template>
</xsl:stylesheet>

Using https://xsltfiddle.liberty-development.net/b4GWVd for conversion i get :

{ "foedselsdato" : "2019-04-22",
    "individId" : "01387",
    "varslinger" : 
    {  } }

But I would like to convert it as below:

[{ "foedselsdato" : "2019-04-22",
    "individId" : "01387",
    "varslinger" : 
    {  } }]

Upvotes: 0

Views: 688

Answers (2)

Kevin Mbugua
Kevin Mbugua

Reputation: 375

The below code worked.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">
  <xsl:output omit-xml-declaration="yes"/>
  <xsl:template match="/">
      <xsl:text>[</xsl:text>
      <xsl:value-of select="xml-to-json(., map { 'indent' : true() })"/>
      <xsl:text>]</xsl:text>
  </xsl:template>
</xsl:stylesheet>

Or

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">
  <xsl:output omit-xml-declaration="yes"/>
  <xsl:template match="/">
      <xsl:text>[</xsl:text>
      <xsl:value-of select="concat('[',xml-to-json(., map { 'indent' : true() }))"/>
      <xsl:text>]</xsl:text>
  </xsl:template>
  </xsl:stylesheet>

Upvotes: 0

Martin Honnen
Martin Honnen

Reputation: 167571

If you want to work with the XDM representation of JSON in XPath 3.1 and XSLT 3 you can use

  <xsl:output method="json" indent="yes"/>

  <xsl:template match="/">
      <xsl:sequence select="array { xml-to-json(.) => parse-json() }"/>
  </xsl:template>

to wrap the previous JSON into an array: https://xsltfiddle.liberty-development.net/b4GWVd/81

Upvotes: 2

Related Questions