groovygroovyshellgroovy-console

groovy convert from csv to json


How can I convert a CSV into JSON and access the objects individually for creating a custom string? In the following code why I cannot view the output of log.info(rows.Id[0]) ?????? When i print it shows me null in console.

data.csv has two columns (ID, Value) with 100 rows.

import groovy.json.JsonOutput
import groovy.json.JsonSlurper
def lines = new File('data.csv').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++]] }
    }

def jsonSlurper = new JsonSlurper()
jsonSlurper = jsonSlurper.parse(JsonOutput.toJson(rows))
log.info(JsonOutput.prettyPrint(JsonOutput.toJson(rows)))
log.info(rows.Id[0])

Solution

  • Your problem here is the use of a GString as key in the map. This looks/prints like a string key, but in terms of identity (how the map looks things up) it is not.

    groovy:000> key = "a"
    ===> a
    groovy:000> ["$key": 1].containsKey(key)
    ===> false
    groovy:000> [(key): 1].containsKey(key)
    ===> true
    

    So use: [(key): vals[i++]] instead.

    Or if you want to golf this further:

    [keys, line.split(',')].transpose().collectEntries()