Groovy web console

subscribe to the feed Subscribe
to this
site

Untitled

Published 3 weeks ago by Gonzalo Andres Vanegas Devia
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 "+--------------+---------+------------+";

//Get info from json and parse data from url
def objectInfo = new JsonSlurper().parseText(url_Json.text)

//get nodes
def listProducts = objectInfo.products
def listOrders = objectInfo.orders

def ItemsOrders = listOrders.collectMany({item -> item.items})
def GroupBy = ItemsOrders.groupBy({item -> item.productId})

def getList = GroupBy.collect({key, val -> [product: key, listOrders: val.size(), quantity: val. quantity.sum()] })

def RowSingle
//iterate collection and if exists calculate the amount of dollars for each product across the orders
listProducts.each({ varItem->
        RowSingle = getList.find({row -> row.product == varItem.id})
        if(RowSingle != null){
           println "| " + varItem.name + " |" + RowSingle.listOrders + "        |US\$" +
              (new Double(RowSingle.quantity) * new Double(varItem.price)).round(2) + "      |";
           println "+--------------+---------+------------+";
        }
        else{
           println "| " + varItem.name + "      |  0 |      0.0|";
           println "+--------------+---------+------------+";
        }   
})