32. JSON payloads that changed shape

PySparkMediumSchema trapNULL trap

json · schema drift · get_json_object · from_json · semi-structured data

Open in Colab
How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

A payments service writes one JSON document per event into a text column. Last year the team restructured the payload: the user and the payment moved into nested objects. Old and new events sit side by side in the same table.

The job that reads them was written for the old shape, with one fixed schema. It still runs. It returns NULL for every field of every new-style event, and nobody noticed until the revenue numbers halved.

Input tables

raw_events

One row per event.

Column Type Description
event_id BIGINT Unique per event.
payload STRING A JSON document. Can be NULL, empty, or not valid JSON.

The two payload shapes:

{"user_id": 12, "amount": 499.0, "currency": "INR"}
{"user": {"id": 12}, "payment": {"amount": 499.0, "currency": "INR"}}

In both shapes the amount is sometimes sent as a string ("499.00"), the user id is sometimes a string ("12"), and the currency is sometimes left out.

Requirement

Return every event with the three fields read from its payload.

  • user_id comes from user_id, or from user.id in the new shape.
  • amount comes from amount, or from payment.amount. A number sent as a string is still a number. Text that is not a number gives NULL.
  • currency comes from currency, or from payment.currency. If the payload states no currency and the amount is not NULL, the currency is INR. If there is no currency and no amount, it is NULL.
  • A field that is missing, or explicitly null, is NULL.
  • A payload that is NULL, empty or not valid JSON gives NULL for all three fields.
  • Every event appears. The job must not fail on a bad payload.

Expected output

One row per event.

Column Type Description
event_id BIGINT
user_id BIGINT
amount DOUBLE
currency STRING INR by default when there is an amount.

Explanation

Show explanationGives the answer away. Try the problem first.

The approach

The payload column does not have one schema. It has two shapes, loose types and some garbage. So do not force one strict schema on it. Read each field from wherever it can be, as text, and convert afterwards.

def field(*paths):
    return F.coalesce(*[F.get_json_object("payload", path) for path in paths])

user_id = field("$.user_id", "$.user.id").try_cast("bigint")
amount = field("$.amount", "$.payment.amount").try_cast("double")

Three things do the work:

  • get_json_object(payload, path) returns the value at one path as a string. It returns NULL when the path is not there, when the value is JSON null, and when the payload is not valid JSON. It never fails.
  • coalesce tries the old path, then the new one. Whichever shape the event has, one of them answers.
  • try_cast turns the string into a number. Because everything comes back as text, it does not matter whether the producer wrote 499.0 or "499.00". Text that is not a number ("free") becomes NULL.

The currency rule is the last line:

currency = F.coalesce(stated_currency, F.when(amount.isNotNull(), F.lit("INR")))

A default belongs to a value. "INR" for an event that has no amount describes nothing.

Of the 121 events, 72 carry the user at the top level, 42 carry it under user, and 7 have neither. 14 send the amount as a string.

Common wrong answers

Reading only the old paths. The job from the story. Every new-shape event comes back with NULLs: 43 rows wrong. The amounts add up to 168,647.81 instead of 274,376.24, and nothing in the logs says so. A path that does not exist is not an error in JSON, it is just an absent value.

from_json with the old schema, typed.

F.from_json("payload", "user_id BIGINT, amount DOUBLE, currency STRING")

Worse than the first: 55 rows wrong. It misses the new shape, and it is strict about types. For {"user_id": 12, "amount": "499.00"} it returns the user and a NULL amount, because a JSON string is not a DOUBLE. For {"user_id": "12", ...} the user is NULL. No error either way.

Plain cast instead of try_cast. In Spark 4 the job stops on the first amount that is not a number: [CAST_INVALID_INPUT] The value 'free' of the type "STRING" cannot be cast to "DOUBLE".

coalesce(currency, "INR") for every row. 8 rows get a currency although they have no amount: the broken payloads, the empty object, the event with only a user. Downstream, a GROUP BY currency now shows INR events with no money in them.

No default at all. 30 events have an amount and no stated currency. They are missing from every per-currency total.

Leaving amount as the string that get_json_object returned. The check reports the type. A number stored as text sorts and compares as text.

The other good solution

from_json is fine if the schema describes both shapes and keeps every leaf as a string:

schema = ("user_id STRING, amount STRING, currency STRING, "
          "user STRUCT<id: STRING>, payment STRUCT<amount: STRING, currency: STRING>")
parsed = F.from_json("payload", schema)

Then coalesce the old and new fields and try_cast, exactly as above. This gives the same result as the reference solution, with one parse of the payload instead of six separate lookups.

json_tuple does not help here: it reads top-level keys only, so it sees nothing of the new shape.

What to do about it for real

Reading both shapes is the repair. The cause is that a producer changed a payload and no consumer found out. Things that prevent the next one:

  • Count what you could not read. amount IS NULL per day, as a metric with an alert, would have caught this on the first day.
  • Keep the raw payload. Because it was stored as text, the old events could be read again with the new logic.
  • A version field in the payload, or a schema registry, so that a change of shape is announced instead of discovered.

Edge cases in the data

Payload Expected (user, amount, currency)
{"user_id": 12, "amount": 49 (cut off) NULL, NULL, NULL
not json, empty string, NULL NULL, NULL, NULL
{} NULL, NULL, NULL
[1, 2, 3] (valid JSON, not an object) NULL, NULL, NULL
{"user_id": 5, "amount": "free"} 5, NULL, NULL
{"user_id": 3, "amount": 100, "currency": null} 3, 100.0, INR
{"user": {"id": 9}} 9, NULL, NULL
{"payment": {"amount": 120.5}} NULL, 120.5, INR
{"user_id": 8, "currency": "USD"} 8, NULL, USD
Amount or user id sent as a string Read as a number.