DataEng Hub
BronzePySparkAbout 20 minutes · pyspark

Flatten nested JSON in PySpark

Turn an orders feed with a nested customer struct and an items array into one flat row per order item.

Scenario

NorthBridge Retail's web shop drops order JSON into the lake. Each document has customer details as a nested object and the basket as an array. Analysts want one flat row per order item.

Input data

{"order_id": "O-1", "customer": {"id": "C-9", "city": "Pune"},
 "items": [{"sku": "A1", "qty": 2, "price": 50.0},
           {"sku": "B2", "qty": 1, "price": 30.0}]}
{"order_id": "O-2", "customer": {"id": "C-4", "city": "Chennai"},
 "items": [{"sku": "A1", "qty": 1, "price": 50.0}]}
Setup script
# Environment: Databricks Runtime 15.x LTS, PySpark
data = [
    ("O-1", {"id": "C-9", "city": "Pune"},
     [{"sku": "A1", "qty": 2, "price": 50.0},
      {"sku": "B2", "qty": 1, "price": 30.0}]),
    ("O-2", {"id": "C-4", "city": "Chennai"},
     [{"sku": "A1", "qty": 1, "price": 50.0}]),
]
df = spark.createDataFrame(data, "order_id string, customer map<string,string>, items array<map<string,string>>")

(Reading the raw JSON with spark.read.json gives proper structs; the map version above is just a quick fixture.)

Task

  1. Produce one row per order item.
  2. Columns: order_id, customer_id, city, sku, qty, line_total (qty × price).

Expected output

order_id customer_id city sku qty line_total
O-1 C-9 Pune A1 2 100.0
O-1 C-9 Pune B2 1 30.0
O-2 C-4 Chennai A1 1 50.0

Constraints

  • No UDFs — built-in functions only.
  • Orders with an empty items array must not disappear silently in your production version (follow-up: which function keeps them?).

Hints

Hint 1

Arrays become rows with one specific function. Structs don't need it — they flatten with plain dot notation.

Hint 2

explode(items) gives one row per element; then reach inside with col("item.sku") and customer.id.

Solution

Show solution
# Environment: Databricks Runtime 15.x LTS, PySpark
from pyspark.sql import functions as F
 
raw = spark.read.json("abfss://lake@acct.dfs.core.windows.net/bronze/orders/")
 
flat = (
    raw
    .select(
        "order_id",
        F.col("customer.id").alias("customer_id"),
        F.col("customer.city").alias("city"),
        F.explode("items").alias("item"),
    )
    .select(
        "order_id", "customer_id", "city",
        F.col("item.sku").alias("sku"),
        F.col("item.qty").cast("int").alias("qty"),
        (F.col("item.qty") * F.col("item.price")).alias("line_total"),
    )
)
flat.display()

Explanation

explode turns each array element into its own row, duplicating the order-level columns. Struct fields need no explode — customer.id is just a column path.

Alternative approaches

  • inline(items) explodes an array of structs straight into columns, skipping the second select.
  • explode_outer keeps orders whose items array is empty or null (row of nulls) — usually what production wants, so dropped orders are visible.

Performance notes

Explode multiplies row count — filter order-level junk before exploding. If items arrays are huge, project only the struct fields you need first to cut shuffle width.

Follow-up questions

  • An upstream change renames qty to quantity for new files only. What happens to your job, and how do you make it loud?

Learn the concept

Keep going

ProblemBronze

Deduplicate a raw events table

Keep exactly one row per event_id — the latest by timestamp — from a bronze table that receives replays and retries.