If the input JSON is of type Object (key-value pairs), it’s parsed to a Map
, so you can use it’s methods to inspect it.
import groovy.json.JsonSlurper
String pfile = """
[{"AUTO":"bmw",
"HOME":"vest",
"JOB":1},
{"AUTO":"audi",
"HOME":"dest",
"JOB":2},
{"AUTO":"opel",
"HOME":"lest",
"JOB":3}]
"""
def jsonSlurper = new JsonSlurper()
def list = jsonSlurper.parseText pfile
List names = list.inject( new HashSet() ){ res, map ->
res.addAll map.keySet()
res
}.toList()
// get types based on actual values
def types = list.first().values()*.getClass()*.simpleName
assert '[AUTO, JOB, HOME]' == names.toString()
assert '[String, String, Integer]' == types.toString()
//reader.outputLinesSetHeaders names, types
list.each{ e ->
//reader.outputLines names.collect{ e[ it ] }
println names.collect{ e[ it ] }
}
//reader.outputLinesEnd()
The lines are commented out to avoid compilation problems.
CLICK HERE to find out more related problems solutions.