我有两个JSON文件:
first.json
[
{"a":"1", "b": "tmp"},
{"a":"2", "b": "tmp"},
{"a":"3", "b": "tmp"}
]
second.json
[
{"c":"1", "d": "tmp"},
{"c":"2", "d": "tmp"},
{"c":"4", "d": "tmp"}
]
output.json
[
{"a":"1", "b": "tmp", "c": "1" , "d": "tmp"},
{"a":"2", "b": "tmp", "c": "2" , "d": "tmp"},
{"a":"3", "b": "tmp", "c": "" , "d": ""}
]
我想基于两个字段-first.json的“ a”和second.json的“ c”在两个json文件first.json和second.json上应用左联接,以将输出作为output.json。如何使用Groovy脚本实现相同的目的?
注意:如果可能,我希望在一行中实现。
答案 0 :(得分:1)
您需要执行以下操作:
def firstJson = '''[
{"a":"1", "b": "tmp"},
{"a":"2", "b": "tmp"},
{"a":"3", "b": "tmp"}
]'''
def secondJson = '''[
{"c":"1", "d": "tmp"},
{"c":"2", "d": "tmp"},
{"c":"4", "d": "tmp"}
]'''
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
def slurpy = new JsonSlurper()
def first = slurpy.parseText(firstJson)
def second = slurpy.parseText(secondJson)
def result = first.collect { f ->
f + (second.find { it.c == f.a } ?: second[0].keySet().collectEntries { [it, ''] })
}
println JsonOutput.toJson(result)