Data science: Totals from JSON orders

An online shop exports its orders as JSON. Work out what each order is worth.

What to build

A program that totals orders read from JSON.

Requirements

  • For each order print order ID (CUSTOMER): TOTAL, where the total is the sum of qty × price over its items, with two decimals.
  • Then print grand total: X (two decimals) and largest order: ID (the first one if several are equal).
  • If there are no orders, print only no orders.

Input

One line: a JSON array of orders, each with "id", "customer" and "items" (a list of objects with "name", "qty" and "price").

Output

The order lines and the two summary lines, or the message.

Constraints

At most 100 orders; quantities and prices are not negative.

Example

Input:

[{"id": 1, "customer": "Asha", "items": [{"name": "pen", "qty": 3, "price": 1.5}, {"name": "book", "qty": 1, "price": 12}]}, {"id": 2, "customer": "Ben", "items": [{"name": "bag", "qty": 1, "price": 25}]}]

Output:

order 1 (Asha): 16.50
order 2 (Ben): 25.00
grand total: 41.50
largest order: 2

Why it works

json.loads turns the nested text into lists and dictionaries, so the totals are a loop over orders with a sum over each order's items.

Examples

Example 1 · Input
[{"id": 1, "customer": "Asha", "items": [{"name": "pen", "qty": 3, "price": 1.5}, {"name": "book", "qty": 1, "price": 12}]}, {"id": 2, "customer": "Ben", "items": [{"name": "bag", "qty": 1, "price": 25}]}]
Expected output
order 1 (Asha): 16.50
order 2 (Ben): 25.00
grand total: 41.50
largest order: 2
Example 2 · Input
[]
Expected output
no orders

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

json.loads(input()) gives a list of dictionaries; each order's "items" is another list.

Hint 2

Keep the largest order with a strict > comparison, so the first one wins a tie.

Solution

Show one correct solution (try it yourself first)
import json

orders = json.loads(input())
if not orders:
    print("no orders")
else:
    grand = 0
    largest = None
    for order in orders:
        total = sum(item["qty"] * item["price"] for item in order["items"])
        grand += total
        print(f"order {order['id']} ({order['customer']}): {total:.2f}")
        if largest is None or total > largest[1]:
            largest = (order["id"], total)
    print(f"grand total: {grand:.2f}")
    print(f"largest order: {largest[0]}")

Lesson: Reading CSV and JSON data →