Groovy web console

subscribe to the feed Subscribe
to this
site

Test Groovy Products Table

Published 1 month ago by Maria Eugenia Perdomo V with tags json array iterate
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 | Total Orders | Unit Price | Quantity | Total Paid |";
println "+--------------+---------+------------------------------------+";

// function return array json from url test
def getProducts(url_json) {

    def products = new JsonSlurper().parse(url_json);

    return products;

}
 //invoke function
ListProducts=getProducts(url_Json);

//unbundle json array
def product= ListProducts.products;
def orders= ListProducts.orders;

//initialize output array
def outPut = [][];

//function process data from products and orders
def processArray(product,orders){
    def out = [][];
    for(def pro: product) {
        nameProduct = pro.name;
        totalOrders = 0;
        totalPrice = 0.0;
        quantityItem = 0;
        unitPrice = pro.price;
        for (def order : orders) {

            for (def item : order.items) {
                if (item.productId == pro.id) {
                    totalOrders = totalOrders + 1;
                    def x = pro.price as Double;
                    def y = item.quantity as Double;
                    def total = x * y;
                    totalPrice = (totalPrice + total).trunc(2);
                    quantityItem = quantityItem + item.quantity;
                }
            }
        }
        out.add([nameProduct, totalOrders as String, unitPrice as String, quantityItem as String, totalPrice as String]);

    }
    return out;
}

//invoke funcion process
outPut=processArray(product,orders);

//iterate output array and print table
outPut.each {
    println "| "+it[0]+" | "+it[1]+" | "+it[2]+ " | "+it[3]+" | "+it[4]+" |";
    println "+--------------+---------+------------------------------------+";

}