1
    {
        "BRANCH": "master",
        "name": "customer",
        "product_name" : "PQ",
        "domain" : "Shopping",
        "_id": "12345"
    }

Given a JSON file containing JSON data to convert into CSV/Excel using Groovy code. Anyone, please help me. I have to convert JSON data into CSV/Excel using Groovy code.

Vy Do
  • 46,709
  • 59
  • 215
  • 313

1 Answers1

1

Solution

JSON is best represented as a map structure, and it is hard to represent a map as a csv. However based off the sample JSON you provide you could use something similar to the following

def jsonSlurper = new groovy.json.JsonSlurper()
def json = jsonSlurper.parseText('{"BRANCH": "master","name": "customer","product_name" : "PQ","domain" : "Shopping","_id": "12345", "asdf":["asdf","asdf"], "obj":{"a":"b", "c":"d"}}')

def result = json.collect { new StringBuilder().append('"').append(it.value).append('"') }.flatten().join(",")

println result

The above code would also work for attributes that are arrays and objects, but entire array/object would be one cell in the CSV file.

output

Chris Maggiulli
  • 3,375
  • 26
  • 39