如何根据 Groovy 脚本中的索引连接两个 json 对象?

How to join two json objects based on index in Groovy script?

我有两个 json 个文件。

一个是InputFile.json:

[{"no":"48","name":"Mahe","Age":"23"},
{"no":"49","name":"Siva","Age":"23"},
{"no":"50","name":"prabhu","Age":"37"}]

另一个是Result.json

{"results":"[
{"Grade":"4","Result":"PASS"},
{"Grade":"5","Result":"FAIL"},
{"Grade":"6","Result":"PASS"}]"
}

因为 json 我需要像下面那样将这两个 json 组合起来..,

[{"no":"48","name":"Mahe","Age":"23","Grade":"4","Result":"PASS"},
{"no":"49","name":"Siva","Age":"23","Grade":"5","Result":"FAIL"},
{"no":"50","name":"prabhu","Age":"37","Grade":"6","Result":"PASS"}]

基于索引结果[0] 将与 InputFile[0] 合并。

现在我已经尝试在 Groovy(ExecuteScript) NiFi 中做到这一点。

无法从 Result.json 获得“4”、“5”、“6”等级索引。

已尝试回答的代码。

def slurper = new groovy.json.JsonSlurper()

def input = slurper.parse(inputFile)
def res = slurper.parse(result)

def joined = [input, res.results].transpose().collect { a, b -> a + b }

我遇到以下问题。

groovy.json.JsonException: expecting '}' or ',' but got current char 'G' with an int value of 71

The current character read is 'G' with an int value of 71
expecting '}' or ',' but got current char 'G' with an int value of 71
line number 2
index number 17
{"Grade":"4","Result":"PASS"},
..^

任何人都可以建议我在 NiFi 中结合这两个 json 的方法吗?

您可以使用 JsonSlurpertranspose

def slurper = new groovy.json.JsonSlurper()

def input = slurper.parse(inputFile)
def res = slurper.parse(result)

def joined = [input, res.results].transpose().collect { a, b -> a + b }

啊,我明白了......在你的例子中,results 出于某种原因被包裹在一个字符串中......所以我们需要 re-parse 该字符串作为 json

这应该适用于这种情况:

def input = slurper.parse(inputFile)
def res = slurper.parseText(slurper.parse(result).results)

def joined = [input, res].transpose().collect { a, b -> a + b }