Skip to content

Instantly share code, notes, and snippets.

@dylanmei
Created March 25, 2014 13:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylanmei/9762211 to your computer and use it in GitHub Desktop.
Save dylanmei/9762211 to your computer and use it in GitHub Desktop.
CSV to JSON in Groovy
import groovy.json.*
if (args.size() == 0) {
println("missing argument")
System.exit(1)
}
def f = new File(args[0])
if (!f.exists()) {
println("file doesn't exist")
System.exit(1)
}
def lines = f.readLines()
def keys = lines[0].split(',')
def rows = lines[1..-1].collect { line ->
def i = 0, vals = line.split(',')
keys.inject([:]) { map, key -> map << ["$key": vals[i++]] }
}
println(JsonOutput.toJson(rows))
@victor-1988
Copy link

Hello,

I tried this code in groovy & it is converting to JSON but everytime it is printing header portion. I don't want to print header, it will print only for 1st time

@victor-1988
Copy link

My sample CSV file is :

firstName,lastName,email,phoneNumber
John,Doe,john@doe.com,0123456789
Jane,Doe,jane@doe.com,9876543210
James,Bond,james.bond@mi6.co.uk,0612345678

When i am executing this code the output is :

[{"firstName":"John","lastName":"Doe","email":"john@doe.com","phoneNumber":"0123456789"},{"firstName":"Jane","lastName":"Doe","email":"jane@doe.com","phoneNumber":"9876543210"},{"firstName":"James","lastName":"Bond","email":"james.bond@mi6.co.uk","phoneNumber":"0612345678"}]

But I want the output should be:

[{"firstName":"lastName":"email":"phoneNumber"},
{"John":"Doe":"john@doe.com":"0123456789"},
{"Jane":"Doe":"jane@doe.com":"9876543210"}]

Any help on this? regarding changes of code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment