1

All of my XSLT is working when using the xml-to-json() function except for this part,

<number key="send_at">
    <xsl:text>1615842000</xsl:text>
</number>

which returns

"send_at":1.615842E9

when I intend to get this result:

"send_at":1615842000
kjhughes
  • 106,133
  • 27
  • 181
  • 240
Jason Gregory
  • 139
  • 1
  • 16

1 Answers1

3

XPath 3.1 (current)

Converting numbers to exponential notation is correct according to the spec (XPath and XQuery Functions and Operators 3.1):

17.5.4 fn:xml-to-json

Rules

Nodes in the input tree are handled by applying the following rules, recursively.

  1. An element $E named number results in the output of the string result of xs:string(xs:double(fn:string($E)))

The fn:xml-to-json function does allow an $options argument, which provides a means for implementation-dependent extensions. Saxon 10.5 already leverages this mechanism to support passing through the value, without regard to JSON validity: 1

map{'number-formatter':function($x){$x}}

XPath 4 (upcoming)

A formatter is an officially supported option to fn:xml-to-json planned for XPath 4: 2

number-formatter: Determines how numeric values should be formatted.

  • Type: (function(xs:string) as xs:string)?
  • Default: ()

1 Thanks to Michael Kay for noting this mechanism (and foreseeing its need (and already implementing it in Saxon 10.5)).
2 Thanks to Martin Honnen for noting this XPath 4 update.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • Or you will have to wait for XPath 4 where https://qt4cg.org/branch/master/xpath-functions-40/Overview-diff.html#func-xml-to-json suggests you can insert your own `number-formatter` that "Determines how numeric values should be formatted:" `Type: (function(xs:string) as xs:string)?` – Martin Honnen Apr 15 '21 at 06:51
  • In fact Saxon 10.5 implements this proposed extension, though it hasn't yet found its way into the documentation. For example you could use `map{'number-formatter':function($x){$x}}` which would output the value as written in the XML (whether or not it is valid in JSON). – Michael Kay Apr 15 '21 at 07:20
  • @kjhughes "There does not appear to be any leeway for implementation-specific options". Actually there is. §1.5 of the F+O spec says "It is not an error if the options map contains options with names other than those described in this specification. Implementations may attach an ·implementation-defined· meaning to such entries..." – Michael Kay Apr 15 '21 at 07:27
  • @MichaelKay, that's cool, even Saxon HE 10.5 seems to output `xml-to-json(1234567, map { 'number-formatter' : function($x) { $x } })` as `1234567`. – Martin Honnen Apr 15 '21 at 07:35
  • @MichaelKay, Martin Honnen: Excellent. Answer updated. Thank you both! – kjhughes Apr 15 '21 at 14:22