Created
March 25, 2014 13:50
-
-
Save dylanmei/9762211 to your computer and use it in GitHub Desktop.
CSV to JSON in Groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.