Veera Induvasi
Veera Induvasi

Reputation: 822

How to fetch value from json string within a xslt

I have below json text

<vtemp>
{ 'Tomatoes': 'yes', 'Banana': 'No', 'Mangoes': 'Yes'}
</vtemp>

and within the xslt need to read this 'Banana' value 'yes' and do some operation example

<xsl:if test="normalize-space('need banana value here')='yes'">
  //my code

</xsl:if>

Upvotes: 0

Views: 913

Answers (1)

Conal Tuohy
Conal Tuohy

Reputation: 3223

In XSLT 3.0, you can use the parse-json() function to parse a JSON object, this will return a map, and you can then extract the value corresponding to the "Banana" key.

However, the content of the vtemp element in your example is not valid JSON according to https://www.rfc-editor.org/rfc/rfc7159.txt because strings are quoted with ' rather than ".

Perhaps translate the ' into " and then use parse-json()? e.g.

Input:

<vtemp>
{ 'Tomatoes': 'yes', 'Banana': 'No', 'Mangoes': 'Yes'}
</vtemp>

Stylesheet:

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

  <xsl:output method="text"/>
  
  <xsl:template match="/">
    <xsl:value-of select="
      vtemp
      => translate(codepoints-to-string(39), codepoints-to-string(34))
      => parse-json()
      => map:get('Banana')
    "/>
  </xsl:template>
  
</xsl:stylesheet>

Output:

No

Upvotes: 1

Related Questions