如何在Groovy中合并2个JSON数组?

时间:2019-03-01 00:49:56

标签: arrays json groovy

尝试以常规方式将2个Json数组合并为1个。

def branchTags = new JsonBuilder()
    branchTags branches, { String branch ->
        tag branch
        type 'b'
    }
    println(branchTags.toString()) 
    //generates [{"tag":"Branch","type":"b"},{"tag":"Branch1","type":"b"}]

    def releaseTags = new JsonBuilder()
    releaseTags releases, {String release ->
        tag release
        type 'r'
    }
    println(releaseTags.toString())
    //generates [{"tag":"Release","type":"r"},{"tag":"Rel1","type":"r"}]

    /*def newTags = new JsonBuilder()
    branchTags.each {k,v -> newTags.}*/
    def slurper = new JsonSlurper()
    def input = slurper.parseText(branchTags.toString())
    def res = slurper.parseText(releaseTags.toString())

    def joined = [input, res].flatten()
    println joined.toString()
    //this generates [{"tag":"Branch","type":"b"},{"tag":"Branch1","type":"b"}][{"tag":"Release","type":"r"},{"tag":"Rel1","type":"r"}]

我需要:

[
   {"tag":"Branch","type":"b"},
   {"tag":"Branch1","type":"b"}, 
   {"tag":"Release","type":"r"},
   {"tag":"Rel1","type":"r"}
]

TIA,

1 个答案:

答案 0 :(得分:2)

在您解析json后的情况下,您有两个数组。

只需使用+将两个数组连接为一个

import groovy.json.*

def branchTags = '[{"tag":"Branch","type":"b"},{"tag":"Branch1","type":"b"}]'
def releaseTags = '[{"tag":"Release","type":"r"},{"tag":"Rel1","type":"r"}]'

def slurper = new JsonSlurper()
def bArr = slurper.parseText(branchTags)
def rArr = slurper.parseText(releaseTags)

def res = bArr+rArr

println new JsonBuilder(res).toString()