Medium: Interview Core · Problem 52 of 82

Order Totals from JSON

MediumErrors and FilesPython

A shop exports its orders as JSON text: a list of orders, each with a "customer" and a list of "items", and each item has a "price" and a "qty":

[{"customer": "Ann", "items": [{"price": 2.5, "qty": 2}, {"price": 1.25, "qty": 4}]}]

Write order_totals(text) that returns a dictionary from customer to the total of price times quantity over all of that customer's orders, rounded to 2 decimals. If the text is not valid JSON, raise a plain ValueError("invalid JSON").

Understand the problem

Look at how JSON maps to Python.

What does json.loads('[{"a": 1}]') return?

  1. A string
  2. A list containing a dictionary
  3. A dictionary

JSON arrays become lists and JSON objects become dictionaries. Numbers become int or float, true and false become True and False, null becomes None.

json.loads("not json") raises json.JSONDecodeError. Which statement is true?

  1. It is a subclass of ValueError
  2. It is a subclass of KeyError
  3. It cannot be caught

JSONDecodeError inherits from ValueError. The task asks for a plain ValueError("invalid JSON"), which hides the library detail from the caller: catch the specific error and raise your own.

Write the solution

Return the totals.

def order_totals(text):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

What are the three levels of nesting, and what do you add up at each one?

Hint 2: the shape of the answer

orders = json.loads(text) inside a try. For each order, for each item, add price * qty to totals[customer] (use get(customer, 0)). At the end round each value.

Reflect

Solution

import json

def order_totals(text):
    try:
        orders = json.loads(text)
    except json.JSONDecodeError:
        raise ValueError("invalid JSON") from None
    totals = {}
    for order in orders:
        amount = sum(item["price"] * item["qty"] for item in order["items"])
        totals[order["customer"]] = totals.get(order["customer"], 0) + amount
    return {customer: round(total, 2) for customer, total in totals.items()}

What this tests: json.loads, nested loops over parsed data, sum with a generator, dict.get, and translating an exception.

raise ... from None hides the original exception from the traceback; plain raise ValueError(...) inside an except block would show both ("During handling of the above exception, another exception occurred"). Use from error to chain them deliberately when the original detail helps.

Parse first, then compute: keep reading data and doing calculations as separate steps. The parsing can fail in one place, and the calculation can be tested without any JSON.

Rounding at the end: adding floats and rounding once is better than rounding every item. (For real money use integers of cents or Decimal.)

What an interviewer might ask next: What if an item is missing "qty"? Decide between raising a clear error and defaulting to 1. (Use item.get("qty", 1) or validate and report the order.)