Get type of value within JSON object using Groovy

Viewed 935

I'm having the following JSON object which I want to check

import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper() 
import groovy.json.JsonOutput;

def object = jsonSlurper.parseText '''
{
  "id" : 10,
  "docType" : "PDF",
  "values" : {
      "color" : "red",
      "pages" : 2,
    },
  "versions" : [
    {
      "verNum" : 1,
      "desc" : "This is the description for it"
    }
  ]
}
'''
// def data = new JsonSlurper().parseText("""[{"a": 1, "b": 2, "c": 3, "x": true}, {"a": 4, "b": 5, "c": 6, "d": "Hello"}]""")
// def content = object.collectEntries{ 
//    it.collectEntries{ 
//        [it.key, it.value.class.name] 
//    } 
//}

//println content

I want to iterate through each of the keys and check for the type using Groovy, for example: id - java.lang.Integer, docType - java.lang.String, values.color - java.lang.String, verNum within the object within the array will be java.lang.Integer

I have searched for a few different ways but most of them won't work in my case. One of them are now commented on as in the code above.

Any suggestion would be much appreciated!

2 Answers

Something like this:

import groovy.json.JsonSlurper

def object = new JsonSlurper().parseText '''
{
  "id" : 10,
  "docType" : "PDF",
  "values" : {
      "color" : "red",
      "pages" : 2,
    },
  "versions" : [
    {
      "verNum" : 1,
      "desc" : "This is the description for it"
    }
  ]
}
'''

def res = [:]
def traverser
traverser = { Map m ->
  m.each{ k, v ->   
    switch( v ){
      case Map:
        res[ k ] = Map
        traverser v
        break
      case List:
        res[ k ] = List
        v.each traverser
        break
      default:
        res[ k ] = v?.getClass()
    }
  }
}

traverser object

def simple = res.collectEntries{ k, v -> [ k, v.simpleName ] }
assert simple.toString() == '[id:Integer, docType:String, values:Map, color:String, pages:Integer, versions:List, verNum:Integer, desc:String]'

I think you should use data variable instead of object in your sample.

def data = new JsonSlurper().parseText("""[{"a": 1, "b": 2, "c": 3, "x": true}, {"a": 4, "b": 5, "c": 6, "d": "Hello"}]""");

def content = data.collectEntries{ 
    it.collectEntries{ 
        [it.key, it.value.class.name];
    } 
}

println content;

The output will be;

[a:java.lang.Integer, b:java.lang.Integer, c:java.lang.Integer, x:java.lang.Boolean, d:java.lang.String]
Related