如何通过XSLT 1.0将JSON报文中的空字符串""替换为null值
XSLT 1.0 实现JSON空字符串转null方案
XSLT 1.0 本身没有内置JSON解析能力,针对你的需求,有两种可落地的实现思路:
方案1:字符串递归替换(适配简单扁平化JSON)
如果你的JSON没有嵌套对象、数组,也不存在字符串内容自带转义双引号的场景,可以直接用递归替换模板处理,代码如下:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="UTF-8" omit-xml-declaration="yes"/> <!-- 入口参数:传入原始JSON字符串 --> <xsl:param name="jsonInput" select="''"/> <xsl:template match="/"> <xsl:call-template name="replaceEmptyStr"> <xsl:with-param name="text" select="$jsonInput"/> </xsl:call-template> </xsl:template> <!-- 递归替换空字符串为null --> <xsl:template name="replaceEmptyStr"> <xsl:param name="text"/> <xsl:choose> <!-- 匹配带空格的": ""格式 --> <xsl:when test="contains($text, ': ""')"> <xsl:value-of select="substring-before($text, ': ""')"/> <xsl:text>: null</xsl:text> <xsl:call-template name="replaceEmptyStr"> <xsl:with-param name="text" select="substring-after($text, ': ""')"/> </xsl:call-template> </xsl:when> <!-- 匹配无空格的":"""格式 --> <xsl:when test="contains($text, ':""')"> <xsl:value-of select="substring-before($text, ':""')"/> <xsl:text>: null</xsl:text> <xsl:call-template name="replaceEmptyStr"> <xsl:with-param name="text" select="substring-after($text, ':""')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$text"/> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>
使用时将你的原始JSON字符串传入jsonInput参数,即可直接输出转换后的结果。
方案2:XML中转方案(适配复杂JSON结构)
如果你的JSON包含嵌套对象、数组、转义字符,推荐走XML中转流程:
- 引入公开的XSLT 1.0通用JSON转XML模板,将输入JSON转换为XML节点结构
- 遍历XML节点时,判断节点文本内容为空的,输出时直接写
null,非空内容按原有格式输出 - 最后用XML转JSON模板把处理后的节点转回JSON格式即可。
内容的提问来源于stack exchange,提问作者Andrey Finkelman
相关产品推荐
相关产品推荐

