JSON 使用 XPath 3.1 进行序列化 fn:serialize

JSON serialization with XPath 3.1 fn:serialize

我在 Saxon-HE 9.8 中使用 XSLT 3.0,并希望在 JSON-LD 中使用 JSON 文档作为链接数据。在 JSON-LD 中,完整的 HTTP URI 通常作为值出现。

当我使用 XPath 3.1 fn:serialize 将数据往返返回 JSON 时,http:// 中的斜线字符被转义。序列化回 JSON 时是否可以避免这种转义?

fn:parse-json 函数有一个 escape 参数,可以设置为 true()false(),但我没有看到任何与 [=13= 类似的东西].

我可以使用 fn:replace 删除转义字符,但想知道是否有我缺少的内置方法。

示例样式表:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:array="http://www.w3.org/2005/xpath-functions/array"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:output="http://www.w3.org/2010/xslt-xquery-serialization"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">

    <xsl:output omit-xml-declaration="yes"/>

    <xsl:variable name="j" expand-text="no"> { "@context": "http://schema.org" } </xsl:variable>

    <xsl:template name="init">
        <xsl:sequence
            select="            
                $j => parse-json(map {'escape': false(), 'liberal': true()})
                => serialize(map {'method': 'json'})
                => replace('\/', '/')
            "/>
    </xsl:template>

</xsl:stylesheet>

没有fn:replace,结果是{"@context":"http:\/\/schema.org"}。使用 fn:replace,结果为 {"@context":"http://schema.org"}

使用 Saxon 9.8,如果 serialize 函数被调用为 => serialize(map {'method': 'json', 'use-character-maps' : map { '/' : '/' }}),则斜线按原样输出,不会转义为 \/

查看规范 https://www.w3.org/TR/xpath-functions-31/#func-serialize explaining the second argument to serialize being a map where the use-character-maps is itself a map(xs:string, xs:string)? and the "keys are the characters to be mapped (as xs:string instances), and whose corresponding values are the strings to be substituted for these characters" and the 3.1 serialization spec 说 "Any character in the string for which character mapping is defined ... is substituted by the replacement string defined in the character map." 和 "Any other character in the input string (but not a character produced by character mapping) is a candidate for [...] JSON escaping."。

所以基本上,如果您将该映射中的字符列为映射到它们自身,JSON 编码将不会进一步改变它们。