Skip to Content
0
Mar 01 at 05:27 PM

Groovy script for Json to CSV conversion

195 Views

Hi Experts I need to convert the below json to CSV using groovy script. My input Json is below

[{ "id":1, "campaign": { "cost":0, "name":"Test1" }, "visitorId":3 }, { "id":2, "campaign": { "cost":0, "name":"Test2" }, "visitorId":5 }]

and i need the out put in the below csv format

id,cost,name,visitorID

1,0,Test1,3

2,0,Test2,5

I am using below groovy script but it gives a different output

def jsonSlurper = new groovy.json.JsonSlurper(); def object = jsonSlurper.parseText(message.getBody(java.lang.String) as String) StringBuilder sb = new StringBuilder() object.each{ sb << it.collect{ it.value } .join(",") .concat("\n")}

message.setBody(sb.toString())

return message

Any help would be highly appreciated