Skip to content
Silver 6 min read · Nested data 2 practice problems ↓

JSON and structs

APIs and event logs send nested data: a customer inside an order, an address inside a customer. Spark keeps that nesting as struct columns. This lesson shows how to reach into structs, how to parse JSON text with a schema, and how to flatten nested data into plain columns.

Step 1 · PySpark functions · Silver · Arrays and nested data, lesson 5 of 5

Read first: select · explode (skip if you know them)

In plain words first

A delivery form has a box called "customer", and inside it smaller boxes: name, and an "address" box with city and pin code. You find the city by going box inside box: customer, then address, then city.

A struct column is that box with boxes inside, and customer.address.city is the path to the one you want.

Structs: a row inside a row

When Spark reads nested JSON or ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more →, objects become struct columns. printSchema() shows them as a tree:

printSchema()

root
 |-- order_id: long
 |-- customer: struct
 |    |-- name: string
 |    |-- address: struct
 |    |    |-- city: string
 |    |    |-- pin: string
 |-- items: array
 |    |-- element: struct
 |    |    |-- sku: string
 |    |    |-- qty: long
PySparkSpark SQL · Reaching into structs
orders.select(
    "order_id",
    F.col("customer.name").alias("customer_name"),
    F.col("customer.address.city").alias("city"),
    "customer.address.*",          # every field of address as its own column
)
SELECT order_id,
       customer.name          AS customer_name,
       customer.address.city  AS city,
       customer.address.*
FROM orders

Build structs with F.struct("a", "b"). A common trick: max(struct(ts, value)) compares structs field by field, so it returns the value of the latest timestamp.

Parsing JSON strings

Kafka messages, API payloads and log lines often arrive as a JSON string column. Spark cannot look inside it until it is parsed:

PySparkSpark SQL · from_json with a schema
schema = "event STRING, user_id BIGINT, props STRUCT<page: STRING, ms: INT>"

events = (raw
    .withColumn("e", F.from_json("value", schema))
    .select("e.event", "e.user_id", "e.props.page", "e.props.ms"))
SELECT e.event, e.user_id, e.props.page, e.props.ms
FROM (SELECT from_json(
               value,
               'event STRING, user_id BIGINT, props STRUCT<page: STRING, ms: INT>'
             ) AS e
      FROM raw)
  • A string that is not valid JSON, or does not fit the schemaschema: The list of a DataFrame's columns and their types, such as order_id: long and city: string. Learn more →, becomes a nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → struct (or nulls in some fields) in the default PERMISSIVE mode. Count them.
  • Fields in the JSON but not in the schema are ignored. That makes the schema a contract: new upstream fields appear only when you add them.
  • F.schema_of_json(F.lit(sample)) infers a schema from one example string, useful to draft the schema once.
  • F.to_json(struct) goes the other way, for example to write a Kafka message.

Flattening an order

Step 1 · parse

Parse the string column into a struct with from_json. One row per order.

The command

order_schema = """order_id INT,
    customer STRUCT<name: STRING>,
    items ARRAY<STRUCT<sku: STRING, qty: INT>>"""

o = raw.select(F.from_json("value", order_schema).alias("o"))

Step 2 · explodeexplode: Turn each element of an array into a row of its own, copying the other columns. Learn more → items

items is an arrayarray: A column that holds a list of values in each row, such as the items of one order. Learn more → of structs. Explode it to get one row per line item; keep the order fields alongside.

The command

lines = o.select("o.order_id", "o.customer", F.explode("o.items").alias("item"))

Step 3 · flatten

Pull the struct fields up into plain columns with dotted paths or .*.

The command

flat = lines.select(
    "order_id", F.col("customer.name").alias("customer_name"), "item.sku", "item.qty"
)

Step 4 · result

A flat table of order lines, ready for joins and aggregationaggregate: A function that turns many rows into one value per group: count, sum, avg, min, max. Learn more →. Use explode_outer in step 2 if orders without items must be kept.

Other options

ToolUse when
get_json_object(col, "$.props.page")You need one or two fields and do not want to write a schema. Parses the string each call, so slower for many fields.
json_tupleSeveral top-level fields at once, without a schema
from_jsonMost cases: typed, parsed once, fast
VARIANT / parse_json (Spark 4.0)The shape changes often or is unknown: store semi-structured data efficiently and query paths later
Note: the in-browser engine does not support structs or JSON functions yet, so the examples in this lesson are read-only. They are standard PySpark and run on any Spark 3.x or 4.x cluster.

Try it yourself

Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.

Goal: Parse JSON strings with a schema, set aside the ones that do not parse, and flatten the nested fields into columns.

Production patternPySpark · Parse JSON with a schema, catch bad records, and flatten
from pyspark.sql import functions as F

raw = spark.createDataFrame([
    ('{"order_id": 1, "customer": {"id": 7, "city": "Pune"},'
     ' "items": [{"sku": "A", "qty": 2}, {"sku": "B", "qty": 1}]}',),
    ('{"order_id": 2, "customer": {"id": 9, "city": "Delhi"}, "items": []}',),
    ('not json at all',),
], ["value"])

schema = """order_id INT,
            customer STRUCT<id: INT, city: STRING>,
            items ARRAY<STRUCT<sku: STRING, qty: INT>>"""
parsed = raw.withColumn("o", F.from_json("value", schema))
bad = parsed.where(F.col("o.order_id").isNull()).select("value")
bad.write.mode("overwrite").text("lab/json/quarantine")

lines = (parsed.where(F.col("o.order_id").isNotNull())
         .select("o.order_id", F.col("o.customer.city").alias("city"),
                 F.explode_outer("o.items").alias("item"))
         .select("order_id", "city", "item.sku", "item.qty"))
lines.write.mode("overwrite").parquet("lab/json/order_lines")
spark.read.parquet("lab/json/order_lines").orderBy("order_id", "sku").show()
print("quarantined:", spark.read.text("lab/json/quarantine").count())

Output from a real run

+--------+-----+----+----+
|order_id| city| sku| qty|
+--------+-----+----+----+
|       1| Pune|   A|   2|
|       1| Pune|   B|   1|
|       2|Delhi|NULL|NULL|
+--------+-----+----+----+

quarantined: 1

What to notice:

  • Order 1 became two rows, one per item (A, B): explode_outer turned the array into rows.
  • Order 2 has no items but kept one row with nulls; plain explode would have dropped it.
  • quarantined: 1: the not json at all line went to the quarantine folder.

Common mistakes

  • Using get_json_object for many fields — Each call re-parses the string. Parse once with from_json.
  • Not counting rows that failed to parse — Invalid JSON becomes null quietly.
  • Explode instead of explode_outer for optional arrays — Orders with no items disappear.
  • Inferring the JSON schema on every run — Slow and unstable. Write the schema down.

Key takeaways

  • Structs are nested rows; reach fields with dotted paths or .*.
  • Parse JSON strings once with from_json and an explicit schema.
  • Explode arrays of structs, then select fields to flatten.
  • Invalid JSON becomes null: count and quarantine it.

Interview prep

THE QUESTION

"A Kafka topic carries JSON order events with an array of items. Produce one row per item."

Cast the value to string, from_json with an explicit schema, explode (or explode_outer) the items array, then select nested fields with dotted paths. Mention handling invalid JSON (null structs, a quarantine table), schema changes (new fields ignored until added to the schema, or VARIANT), and that explode multiplies rows so later aggregations must account for it.

Avoid: parsing JSON with a UDF and json.loads. from_json with a schema is faster and stays in the JVM.

Follow-ups · answer out loud, then open

Follow-up"How do you get the schema to pass to from_json?"
Write it as a DDL string or StructType, or infer it once with schema_of_json on a representative sample, review it, and pin it in code. Do not infer per run.
Scenario"Producers add new fields to the JSON every month. How do you keep up?"
Fields not in your schema are ignored, so nothing breaks, but you lose them. Options: keep the raw string or a VARIANT column alongside parsed fields, update the schema deliberately, and alert on unknown fields by comparing to schema_of_json on recent data.
Trap"from_json raises an error on invalid JSON."
In the default PERMISSIVE mode it returns null (or a struct of nulls) for invalid input. Count those nulls; they are silent data loss otherwise.

Check yourself

3 questions

How do you select every field of the struct column address as separate columns?

Show the answer

select("address.*"). The .* expands a struct into its fields.

What does from_json return for a string that is not valid JSON (default mode)?

Show the answer

null. Invalid input becomes null in PERMISSIVE mode.

Why prefer from_json over many get_json_object calls?

Show the answer

It parses the string once instead of once per call. Each get_json_object call parses the JSON again.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · new module: Reshape and refine · 4 min read
coalesce
Take the first non-null value from several columns, and why it is not the same as fillna.

Related lessons

Previous: Array functions

Primary sources: functions.from_json · JSON files