Skip to Content
0
Aug 02, 2023 at 06:13 AM

Groovy script with dynamic keys

86 Views

I am having a working function that goes like the following. In step 1 I transform the date and in step 2 I build the JSON.

Q1. Is there a way to do both in one loop ?.

Q2. Is there a way to point to ZCOUNTRYCODE or ZPERIOD_TSTAMP key names by parameters - say we do not know the key names in advance ?

any ideas are appreciated

 
 def Message transformToTarget(Message message) {
    
    def body = message.getBody(java.io.Reader);
    Map ibpInput = new JsonSlurper().parse(body); 
    def result_array = ibpInput.get("d").get("results")
    // Step 1- Transform the payload
    def data_raw = result_array.collect {[
            "Code": it.ZCOUNTRYCODE,
            "TimeStamp": convertMilliToDate(it.ZPERIOD_TSTAMP)
    ] }
    
    // Step - 2 Convert to JSON
    def builder = new JsonBuilder();
    builder 
    { 
            Countries(data_raw) 
            { 
                this_result ->
                    Code(this_result.Code)
TimeStamp(this_result.TimeStamp)
} } def prettyBody = builder.toPrettyString() message.setBody(prettyBody); return message; }