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

Apache Nifi如何将JSON数组转换为指定键名的JSON对象

NiFi JSON数组转带序号键对象方案

最优处理器选择

优先使用JoltTransformJSON处理器,它是NiFi原生专为JSON结构转换设计的处理器,纯Java实现无额外脚本引擎开销,吞吐性能远高于各类脚本类处理器,是该场景下的效率最优选择。

转换脚本/规范编写

方案1:JoltTransformJSON 转换规范(性能最优)

如果需要数组索引从0开始对应key0,使用以下最简规范:

[
  {
    "operation": "shift",
    "spec": {
      "*": "key&0"
    }
  }
]

如果需要数组第一个元素(索引0)对应key1,使用以下规范:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "$": "idx",
        "@": "val"
      }
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "idx": ["=toInteger", "=sum(1)"]
    }
  },
  {
    "operation": "shift",
    "spec": {
      "val": "key@(1,idx)"
    }
  }
]

规范说明:

  • 第一步将数组的索引和对应值分别暂存到idx和val字段
  • 第二步将索引值加1完成序号偏移
  • 第三步将值映射为key+偏移后序号的键值对

方案2:ExecuteGroovyScript 脚本(灵活性更高)

如果后续有自定义逻辑扩展需求,可使用Groovy脚本实现,性能仅次于Jolt方案,脚本代码如下:

import groovy.json.JsonSlurper
import groovy.json.JsonBuilder

def flowFile = session.get()
if (!flowFile) return

try {
    def inputArr = session.read(flowFile).withStream { new JsonSlurper().parse(it) }
    def outputMap = [:]
    inputArr.eachWithIndex { item, index ->
        outputMap["key${index + 1}"] = item
    }
    flowFile = session.write(flowFile, { outputStream ->
        outputStream.write(new JsonBuilder(outputMap).toString().getBytes("UTF-8"))
    } as OutputStreamCallback)
    session.transfer(flowFile, REL_SUCCESS)
} catch (Exception e) {
    session.transfer(flowFile, REL_FAILURE)
}

内容的提问来源于stack exchange,提问作者Jens Marco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 20:15:11