0

I am trying to parse nested JSON to CSV, using XSLT transformation. In this particular case each child object counting from "datasheet", e.g. "result-sheet" and "balance-sheet", should end up in one CSV file (output) each. Currently I am however just elaborating getting out "result-sheet" only.

I noticed that the content of arrays are getting merged togehter.

Data:

<data>
{
  "datasheets": {
    "result-sheet": {"bank": [1,3], "credit": [2,6]},
    "balance-sheet": {"loans": [4,5], "inventory": [9,0]}
  }
}
</data>

XSL:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:array="http://www.w3.org/2005/xpath-functions/array"
  >

<xsl:output method="text" indent="yes"/>
<xsl:mode on-no-match="shallow-skip"/>

    <!-- Parse JSON to XML -->
    <xsl:template match="data">
          <xsl:apply-templates select="json-to-xml(.)"/>
    </xsl:template>

  <xsl:template match="*">
    <h2>Result sheet</h2>
    <xsl:text>&#xa;</xsl:text>
    <xsl:value-of select="*/(string-join(head(*)/*/@key, ','), *!string-join(*, ','))" separator="&#10;"/>
  </xsl:template>
</xsl:stylesheet>

Result:

Result sheet
bank,credit
13,26
45,90

Wanted result:

bank,credit
1, 2,
3, 6

1 Answer 1

1

I don't quite understand which data you want to have in each line, the following templates creates a line using for-each-pair on each pair of fn:number elements in the two fn:array children of the fn:map with the @key being result-sheet:

  <xsl:template match="*:map[@key = 'result-sheet']">
    <xsl:value-of select="for-each-pair(*:array[1]/*:number, *:array[2]/*:number, function($n1, $n2) { $n1 || ', ' || $n2 })"
      separator="&#10;"/>
  </xsl:template>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.