You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过XSLT映射移除JSON中的{"root":节点与空字符串元素

使用XSLT处理JSON:移除外层root节点及数组空元素

输入JSON示例

{
   "root": [
      {
         "TPDName": "160 TPD ",
         "LineName": "J20",
         "JobName": "120 ML HIMALAYA [PLAIN] -DS120",
         "PONumber": "000009000162",
         "OLDPONumber": "000001003901",
         "FGCode": "A3W0254QNPQ000001X",
         "OfferedDate": "2023-12-06T11:38:33.00Z",
         "HourlyProductionInspectionLotNumber": "040000013878",
         "PaletteQuantities": {
            "PaletteNumber": 285,
            "Quantity": "10 ",
            "HUNumber": 1000102548
         },
         "ProductCode": "A3W0254QNPQ000001X"
      },
      ""
   ]
}

实现XSLT代码

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="json" indent="yes"/>

  <xsl:template match="/">
    <!-- 解析输入JSON为XDM结构 -->
    <xsl:variable name="input-json" select="parse-json(.)"/>
    <!-- 提取root数组并过滤空字符串元素 -->
    <xsl:variable name="filtered-items" select="$input-json?root[. castable as map(*) or . castable as array(*)]"/>
    <!-- 将过滤后的元素序列化为JSON数组输出 -->
    <xsl:sequence select="array {$filtered-items}"/>
  </xsl:template>
</xsl:stylesheet>

代码说明

  • parse-json(.):将输入的JSON文本转换为XDM(XPath Data Model)的映射/数组结构,方便后续处理
  • $input-json?root:通过XPath 3.1的映射访问语法,获取外层root对应的数组
  • 过滤条件[. castable as map(*) or . castable as array(*)]:只保留数组中属于对象(map)或数组类型的元素,自动排除空字符串这类原子值
  • array {$filtered-items}:将过滤后的元素重新包装为数组,最终序列化为JSON格式输出

处理后输出结果

[
  {
    "TPDName": "160 TPD ",
    "LineName": "J20",
    "JobName": "120 ML HIMALAYA [PLAIN] -DS120",
    "PONumber": "000009000162",
    "OLDPONumber": "000001003901",
    "FGCode": "A3W0254QNPQ000001X",
    "OfferedDate": "2023-12-06T11:38:33.00Z",
    "HourlyProductionInspectionLotNumber": "040000013878",
    "PaletteQuantities": {
      "PaletteNumber": 285,
      "Quantity": "10 ",
      "HUNumber": 1000102548
    },
    "ProductCode": "A3W0254QNPQ000001X"
  }
]

注意事项

需要使用支持XSLT 3.0和XPath 3.1的处理器,比如Saxon-HE 9.8及以上版本,才能正常解析和处理JSON数据。

内容的提问来源于stack exchange,提问作者Bhagwandas Rathor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 13:37:47