prime
prime

Reputation: 799

Merge two JSONs from groovy

I have 2 JSON files and I want to merge those 2 and create one JSON message using groovy. Based on the "type" value I'm going to merge those two JSON files.

Input JSON message1

{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]

Input JSON message2

[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]

Expected JSON

{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"},{"name":"SecondFile","type": "error"}]}

I used the below groovy code.

JsonBuilder jsonBuilder = new JsonBuilder(JSON1)
jsonBuilder.content.message= JSON2
def updatedBody = jsonBuilder.toString()

From the above code, I got the below message.

{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]}

Any help sorting this would be much appreciated.

Upvotes: 0

Views: 5322

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42491

Try using JsonSlurper:

import groovy.json.*

​def json1 = '{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]}'​​​​​​​​​​​​​
def json2 = '[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]'
def slurper = new JsonSlurper()
def json1Obj = slurper.parseText(json1)
def json2Obj = slurper.parseText(json2)
json1Obj.message+=json2Obj
println JsonOutput.toJson​(json1Obj)​

This prints:

{"message":[{"name":"HelloFile","type":"input"},{"name":"SecondFile","type":"error"},{"name":"NewFile","type":"input"},{"name":"MyFile","type":"output"}]}

Upvotes: 1

Related Questions