how do i list json field names and values?

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 =  """
def jsonSlurper = new JsonSlurper()
def list = jsonSlurper.parseText pfile

List names = list.inject( new HashSet() ){ res, map ->
  res.addAll map.keySet()

// 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 ] }


The lines are commented out to avoid compilation problems.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top