Groovy web console

subscribe to the feed Subscribe
to this
site

Groovy Json with grouby, sum, count with nested, merge & many collection

Published 2 weeks ago by jthemaster with tags Groovy nested Json collection outerjoin merge many
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper
def url_Json = new URL("https://www.tailorsoft.co/sample.json")
 
// Print the table header
println "+--------------+---------+------------+";
println "| Product      |  Orders |      Total |";
println "+--------------+---------+------------+";


def json= new JsonSlurper().parseText(url_Json.text)

/* collectMany directly flatten the two sublists 
 */
def result = json.orders.collectMany{ X->
    // collect returns a list of N (in this example, N=2) elements 
    // [ [ orders1: ..., productId1: ..., quantity1: ... ],
    //   [ orders2: ..., productId2: ..., quantity2: ... ] ]
    X.items.collect{ Y->
            // return in [ productId: ..., orders: ..., quantity: ... ]
        [ id: Y.productId] +
        [ orden: X.id] + 
        [ quant: Y.quantity] 
    }
}.groupBy({ user ->
    // Group by id
    user.id
    }).sort().collect { k, v -> 
    // Sum Quantity by product 
    // Total Order by Prodcut
    [id:k] + 
    [OT:v.orden.size()] + 
    [QT:v.quant.sum()]
}

//Merge collection 
def resultd = (json.products +  result).groupBy { it.id}
    .values()
    *.sum()
    .collect { it << 
    ['DT': (Double.parseDouble(it.price)*(it.QT?:0)).round(1) ] 
}

//Print the report
resultd.each{ F->
    println([ (F.name?:0).padRight(14) ] + 
    [(F.OT?:0).toString().center(8)] + 
    [(F.DT?:0).toString().padLeft(11)]) 
}
/** Stackoverflow tocpics merge, nested, many, groupby and Countby Collection Groovy
*Is the first time that i work with Groovy 
*Im publish the solution wiht my user jthemaster on:
https://stackoverflow.com/questions/62652679/groovy-json-with-grouby-sum-count-with-nested-merge-many-collection
**/

/*reference:
*https://stackoverflow.com/questions/42210857/groovy-way-to-merge-two-lists-of-maps-with-some-calculations
*https://stackoverflow.com/questions/40100943/groovy-groupby-multiple-field
*http://docs.groovy-lang.org/next/html/documentation/working-with-collections.html#JN1035-Maps-Collectionviewsofamap
*/