How do I change the type of a variable in map that is in list?

158 views Asked by At

Json has only integer and string. I have a "list", inside which "map", I did not attach data, because they can be any. The question is that I have a date inside this "list" of type "String", how can I change to type "Date"? In the code list.each and map.each, values at a certain step will be a date value of type String, I can check for a date with a regular expression, but how can I change it to Date? map.put?

def list = jsonSlurper.parseText JSON
 def typeMap = [:].withDefault { key -> "String" }
            list.each { map ->
                map.each { key, values ->
                    if (values != null) {
                        typeMap[key] = getTypeDef(values)
                        println('value ' + values + ' typeMap ' + typeMap[key])
                        //typeMap[key] = values.getClass().simpleName
                    }
                }
            }

A regex to test that values will be masked with a date to change the type.

if (values ==~ /^(0?[1-9]|[12][0-9]|3[01])[\\/\-.](0?[1-9]|1[012])[\\/\-.]\d{4}\s[0-2]?[0-9]:[0-5][0-9]:[0-5][0-9]\u0024/){}
1

There are 1 answers

0
daggett On

not optimal, but for small jsons should work

import groovy.json.*

def JSON='''
{"a":[{"d1":"2021-02-25 18:56:13","s":"s123","i":456}]}
'''

def detectDates(Object o){
    if(o instanceof List)return o.collect{ detectDates(it) }
    if(o instanceof Map)return o.collectEntries{k,v-> [k,detectDates(v)] }
    if(o instanceof String && o==~/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/)return Date.parse('yyyy-MM-dd HH:mm:ss',o)
    return o
}

def o = new JsonSlurper().parseText(JSON)

assert o.a[0].d1 instanceof String
o = detectDates(o)
assert o.a[0].d1 instanceof Date
println new JsonBuilder(o).toPrettyString()