Explode Nested JSON Arrays — Practice Questions
1 free PYSPARK challenge on Explode Nested JSON Arrays, auto-graded in the browser. Each states the problem, shows the input and expected output, and explains the answer.
- Explode Order Items Array into Individual Rows — Easy · PYSPARK · +50 XP
How to explode nested JSON arrays
API responses and event logs often store several values inside one field: an order with an array of items, or a user with a list of tags. Analysis tools need one value per row, so flattening nested data is a routine part of data engineering. In PySpark, the explode function does this by producing one output row for each element in an array, repeating the other columns alongside it.
Start from the schema, not the data. Call printSchema, or define the schema yourself when you read JSON, because inference on a sample can guess a type wrongly and later records then fail or become null. Fields inside a struct are reached with dot notation, such as customer.city, and do not need exploding at all. Only arrays and maps change the number of rows. When a JSON document arrives as a string column, parse it first with from_json and an explicit schema.
The most common mistake is losing rows. Plain explode drops any row whose array is null or empty, so an order with no items silently vanishes from the output. If those rows must survive, use explode_outer, which keeps them and returns null for the exploded column. Use posexplode when the position in the array matters, as it adds the element's index as a separate column. When an array holds structs, explode it first and then select the fields with dot notation, or use a star expansion such as item.* to promote them all to top-level columns.
Be careful with row counts, because explode multiplies data. If you explode two independent arrays one after the other, you get a cross product of their elements, which is rarely what anyone wants. To pair two arrays by position, combine them with arrays_zip and explode once. Exploding large arrays also inflates the data early in a job, so filter and select before you explode wherever you can. If you group the exploded rows back together afterwards, ask whether a higher-order function such as transform or filter could work on the array directly and avoid the expansion altogether.
Worked example
from pyspark.sql import functions as F
rows = [(1, [("pen", 2), ("ink", 1)]), (2, [])]
schema = "order_id INT, items ARRAY<STRUCT<sku: STRING, qty: INT>>"
orders = spark.createDataFrame(rows, schema)
orders.select("order_id", F.explode_outer("items").alias("item")) \
.select("order_id", "item.sku", "item.qty").orderBy("order_id", "sku").show()
Output
+--------+----+----+
|order_id| sku| qty|
+--------+----+----+
| 1| ink| 1|
| 1| pen| 2|
| 2|NULL|NULL|
+--------+----+----+
Preparing for an interview? PySpark coding interview questions · online PySpark compiler.