ShopKart's app sends JSON
Besides the nightly order files, the ShopKart mobile app and website send an event every time a customer opens the app, searches or checks out. Events are JSON, one per line, and not all of them have the same fields: only checkouts have items, only some have a coupon, and website events have no app_version.
{"event_id": 1, "type": "app_open", "customer_id": 58, "ts": "2026-11-24T13:07:00", "device": {"os": "ios", "app_version": "5.3.0"}}
{"event_id": 2, "type": "app_open", "customer_id": 101, "ts": "2026-11-24T22:41:00", "device": {"os": "android", "app_version": "5.3.0"}}
{"event_id": 3, "type": "checkout", "customer_id": 129, "ts": "2026-11-24T08:20:00", "device": {"os": "android", "app_version": "5.3.0"}, "items": [{"product_id": 8, "qty": 2}, {"product_id": 1, "qty": 1}, {"product_id": 4, "qty": 1}]}Forcing this into fixed columns would break the day the app adds a field. Instead we keep each event whole and pull out what we need.
📱App events
JSON lines, fields vary
🧩raw.events
One VARIANT column: nothing lost
🧹analytics.checkout_items
Typed columns, one row per item
Load JSON into a VARIANT column
We reuse the landing stage from lesson 4 with a JSON file format. First, let Snowflake look at the files:
USE SCHEMA shopkart.raw;
CREATE OR REPLACE FILE FORMAT json_lines TYPE = JSON; -- one JSON object per line
PUT file://~/shopkart/data/events/events_*.json @landing/events/ AUTO_COMPRESS = TRUE;
-- Let Snowflake guess the columns from the files
SELECT column_name, type, nullable
FROM TABLE(INFER_SCHEMA(LOCATION => '@landing/events/', FILE_FORMAT => 'json_lines'))
ORDER BY column_name;| COLUMN_NAME | TYPE | NULLABLE |
|---|---|---|
| coupon | TEXT | True |
| customer_id | NUMBER(3, 0) | True |
| device | OBJECT | True |
| event_id | NUMBER(3, 0) | True |
| items | ARRAY | True |
| query | TEXT | True |
| ts | TIMESTAMP_NTZ | True |
| type | TEXT | True |
INFER_SCHEMA found every key across all files, including ones only some events have. Handy for exploring, and it can even generate a table (CREATE TABLE ... USING TEMPLATE). But we'll load the raw JSON as-is:
-- One VARIANT column holds each whole JSON event, plus where it came from
CREATE OR REPLACE TABLE events (
v VARIANT,
source_file VARCHAR,
loaded_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()
);
COPY INTO events (v, source_file)
FROM (SELECT $1, METADATA$FILENAME FROM @landing/events/)
FILE_FORMAT = (FORMAT_NAME = 'json_lines');
SELECT COUNT(*) AS events FROM events;
SELECT v FROM events WHERE v:type = 'checkout' ORDER BY v:event_id LIMIT 1;| file | status | rows_parsed | rows_loaded |
|---|---|---|---|
| landing/events/events_2026-11-24.json.gz | LOADED | 40 | 40 |
| … 6 more daily files | LOADED | 40 | 40 |
| EVENTS |
|---|
| 280 |
{
"customer_id": 129,
"device": {
"app_version": "5.3.0",
"os": "android"
},
"event_id": 3,
"items": [
{ "product_id": 8, "qty": 2 },
{ "product_id": 1, "qty": 1 },
{ "product_id": 4, "qty": 1 }
],
"ts": "2026-11-24T08:20:00",
"type": "checkout"
}The whole event is in one column. (Snowflake shows object keys in alphabetical order; the data is the same.) We also kept source_file and loaded_at: when something looks wrong later, you can trace it back to the exact file.
Read fields with paths and casts
-- Read fields with : (first level) and . (deeper), then cast with ::
SELECT v:event_id::NUMBER AS event_id,
v:type::VARCHAR AS type,
v:device.os::VARCHAR AS os,
v:device.app_version::VARCHAR AS app_version,
v:ts::TIMESTAMP_NTZ AS ts
FROM events
ORDER BY event_id
LIMIT 5;| EVENT_ID | TYPE | OS | APP_VERSION | TS |
|---|---|---|---|---|
| 1 | app_open | ios | 5.3.0 | 2026-11-24 13:07:00 |
| 2 | app_open | android | 5.3.0 | 2026-11-24 22:41:00 |
| 3 | checkout | android | 5.3.0 | 2026-11-24 08:20:00 |
| 4 | app_open | ios | 5.3.0 | 2026-11-24 15:25:00 |
| 5 | checkout | ios | 5.2.1 | 2026-11-24 14:55:00 |
| Syntax | Means |
|---|---|
| v:type | Key type at the top level |
| v:device.os | Key os inside the device object |
| v['device']['os'] | Same thing, bracket style (needed for keys with spaces or dashes) |
| v:items[0] | First element of an array (positions start at 0) |
| ::VARCHAR, ::NUMBER, ::TIMESTAMP_NTZ | Cast the JSON value to a normal type |
Two traps everyone falls into
-- Without ::VARCHAR you get a JSON value (with quotes)
SELECT v:type AS without_cast, v:type::VARCHAR AS with_cast FROM events LIMIT 1;
-- Paths are case-sensitive: "Type" is not "type"
SELECT v:Type AS wrong_case, v:type::VARCHAR AS right_case FROM events LIMIT 1;| WITHOUT_CAST | WITH_CAST |
|---|---|
| "app_open" | app_open |
| WRONG_CASE | RIGHT_CASE |
|---|---|
| NULL | app_open |
Paths work anywhere a column does, including GROUP BY:
SELECT v:type::VARCHAR AS type, v:device.os::VARCHAR AS os, COUNT(*) AS events
FROM events
GROUP BY 1, 2
ORDER BY 1, 2;| TYPE | OS | EVENTS |
|---|---|---|
| app_open | android | 35 |
| app_open | ios | 47 |
| app_open | web | 29 |
| checkout | android | 32 |
| checkout | ios | 19 |
| checkout | web | 33 |
| search | android | 23 |
| search | ios | 30 |
| search | web | 32 |
Arrays: LATERAL FLATTEN
A checkout has a list of items. To count units per product we need one row per item. FLATTEN does that; LATERAL means “for each row on the left, flatten its array”.
-- One row per item inside each checkout: LATERAL FLATTEN
SELECT e.v:event_id::NUMBER AS event_id,
i.index AS position,
i.value:product_id::NUMBER AS product_id,
i.value:qty::NUMBER AS qty
FROM events e,
LATERAL FLATTEN(input => e.v:items) i
WHERE e.v:event_id::NUMBER IN (3, 5)
ORDER BY event_id, position;| EVENT_ID | POSITION | PRODUCT_ID | QTY |
|---|---|---|---|
| 3 | 0 | 8 | 2 |
| 3 | 1 | 1 | 1 |
| 3 | 2 | 4 | 1 |
| 5 | 0 | 3 | 2 |
| 5 | 1 | 4 | 1 |
| 5 | 2 | 11 | 1 |
Two events became six rows. FLATTEN gives each element as value, its position as index (plus key, path and this). Now join to a normal table like any other rows:
-- Which products sell most in app checkouts? JSON joined to a normal table
SELECT p.name,
SUM(i.value:qty::NUMBER) AS units,
SUM(i.value:qty::NUMBER * p.price) AS revenue
FROM events e,
LATERAL FLATTEN(input => e.v:items) i
JOIN products p ON p.product_id = i.value:product_id::NUMBER
WHERE e.v:type::VARCHAR = 'checkout'
GROUP BY p.name
ORDER BY revenue DESC
LIMIT 5;| NAME | UNITS | REVENUE |
|---|---|---|
| Silk Saree | 29 | 101471.00 |
| Smartwatch | 18 | 89982.00 |
| Denim Jacket | 27 | 51273.00 |
| Running Shoes | 23 | 50577.00 |
| Wireless Earbuds | 17 | 42483.00 |
Missing keys and OUTER
-- A key that isn't there is just NULL
SELECT COALESCE(v:coupon::VARCHAR, '(none)') AS coupon, COUNT(*) AS checkouts
FROM events
WHERE v:type::VARCHAR = 'checkout'
GROUP BY 1
ORDER BY checkouts DESC;| COUPON | CHECKOUTS |
|---|---|
| (none) | 52 |
| DIWALI10 | 16 |
| WINTER15 | 16 |
-- Events with no "items" vanish from a FLATTEN... unless OUTER => TRUE
SELECT COUNT(*) AS rows_inner FROM events e, LATERAL FLATTEN(input => e.v:items) i;
SELECT COUNT(*) AS rows_outer FROM events e, LATERAL FLATTEN(input => e.v:items, OUTER => TRUE) i;| ROWS_INNER |
|---|
| 171 |
| ROWS_OUTER |
|---|
| 367 |
171 items came from the checkouts. The other 196 events (app opens and searches) have no items, so a plain FLATTEN drops them, just like an inner join. OUTER => TRUE keeps them with NULLs (171 + 196 = 367), like a left join. Use it when you're counting events, not items.
When the app adds a field
-- The app adds a new field, "payment". Let's insert a test event...
INSERT INTO events (v, source_file)
VALUES (PARSE_JSON('{"event_id": 281, "type": "checkout", "customer_id": 7, "ts": "2026-12-01T10:00:00", "device": {"os": "android", "app_version": "5.4.0"}, "items": [{"product_id": 3, "qty": 1}], "payment": {"method": "UPI"}}'), 'manual');002014 (22000): SQL compilation error:
Invalid expression [PARSE_JSON('{"event_id": 281, ... "payment": {"method": "UPI"}}')] in VALUES clause-- PARSE_JSON isn't allowed in VALUES: use INSERT ... SELECT instead
INSERT INTO events (v, source_file)
SELECT PARSE_JSON('{"event_id": 281, "type": "checkout", "customer_id": 7, "ts": "2026-12-01T10:00:00", "device": {"os": "android", "app_version": "5.4.0"}, "items": [{"product_id": 3, "qty": 1}], "payment": {"method": "UPI"}}'), 'manual';
-- No ALTER TABLE needed: the new field is simply there
SELECT v:event_id::NUMBER AS event_id,
v:payment.method::VARCHAR AS payment_method,
TYPEOF(v:payment) AS payment_type
FROM events
WHERE v:event_id::NUMBER IN (280, 281)
ORDER BY event_id;| EVENT_ID | PAYMENT_METHOD | PAYMENT_TYPE |
|---|---|---|
| 280 | NULL | NULL |
| 281 | UPI | OBJECT |
Version 5.4.0 of the app sends payment; older events don't. No table change, no failed load. That's schema-on-read: you decide the structure when you query, not when you load. TYPEOF tells you what kind of value a path holds.
Make it easy for everyone: a typed table
Analysts shouldn't have to remember LATERAL FLATTEN and casts. Do the work once and save a clean table in the analytics schema:
-- Turn JSON into a clean, typed table once, so every report uses normal columns
CREATE OR REPLACE TABLE shopkart.analytics.checkout_items AS
SELECT e.v:event_id::NUMBER AS event_id,
e.v:ts::TIMESTAMP_NTZ::DATE AS event_date,
e.v:customer_id::NUMBER AS customer_id,
e.v:device.os::VARCHAR AS os,
e.v:coupon::VARCHAR AS coupon,
i.value:product_id::NUMBER AS product_id,
i.value:qty::NUMBER AS qty
FROM events e,
LATERAL FLATTEN(input => e.v:items) i
WHERE e.v:type::VARCHAR = 'checkout';
SELECT * FROM shopkart.analytics.checkout_items ORDER BY event_id, product_id LIMIT 4;| EVENT_ID | EVENT_DATE | CUSTOMER_ID | OS | COUPON | PRODUCT_ID | QTY |
|---|---|---|---|---|---|---|
| 3 | 2026-11-24 | 129 | android | NULL | 1 | 1 |
| 3 | 2026-11-24 | 129 | android | NULL | 4 | 1 |
| 3 | 2026-11-24 | 129 | android | NULL | 8 | 2 |
| 5 | 2026-11-24 | 153 | ios | NULL | 3 | 2 |
In lessons 7 and 8 you'll make this table update itself automatically as new events arrive, instead of rebuilding it by hand.
Going the other way: rows to JSON
-- The other direction: build JSON from rows (for an API or a file export)
SELECT OBJECT_CONSTRUCT(
'customer_id', customer_id,
'items', ARRAY_AGG(OBJECT_CONSTRUCT('product_id', product_id, 'qty', qty))
WITHIN GROUP (ORDER BY product_id)
) AS cart
FROM shopkart.analytics.checkout_items
WHERE event_id = 3
GROUP BY customer_id;{
"customer_id": 129,
"items": [
{ "product_id": 1, "qty": 1 },
{ "product_id": 4, "qty": 1 },
{ "product_id": 8, "qty": 2 }
]
}| Function | Does |
|---|---|
| PARSE_JSON(text) | Text → VARIANT |
| TO_JSON(variant) | VARIANT → JSON text |
| OBJECT_CONSTRUCT(k, v, ...) | Build an object from columns |
| ARRAY_AGG(x) | Collect many rows into one array |
| ARRAY_SIZE(arr) | Number of elements |
| OBJECT_KEYS(obj) | List an object's keys |
| TRY_PARSE_JSON(text) | Like PARSE_JSON, but returns NULL for broken JSON instead of failing |
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1How do you load and query JSON in Snowflake?Fresher+
Q2What is the VARIANT data type?Fresher+
Q3Explain LATERAL FLATTEN with an example.1–3 yrs+
Q4How do you handle schema changes in JSON sources?1–3 yrs+
Q5Why does a JSON field return NULL even though it's in the data?1–3 yrs+
Q6Should JSON stay in VARIANT for analytics, or be flattened into tables?3+ yrs+
Key takeaways
- ✓VARIANT lets you load JSON without deciding the structure first.
- ✓Paths plus casts read any field; FLATTEN turns lists into rows.
- ✓Mind case-sensitive keys and inner-join behaviour of FLATTEN.
- ✓Raw JSON in, typed tables out: the standard pattern.
Frequently asked questions
What is VARIANT in Snowflake?
A column type that can hold any semi-structured value: a JSON object, an array, a string, a number, true/false or null, up to 128 MB per value (16 MB in older accounts). Snowflake stores it in an optimised, columnar way, so queries on fields inside it are still fast.
What does LATERAL FLATTEN do?
It turns an array (or object) inside a row into one row per element. Each output row has columns like VALUE (the element), INDEX (its position) and KEY (for objects). It's how you query lists, like the items in an order.
Should I keep data as VARIANT or turn it into columns?
Both. Land raw JSON in a VARIANT column (nothing is lost when the app adds fields), then build typed tables with normal columns for the fields reports use. Analysts get simple, fast columns, and you can always re-derive them from the raw data.
Why does my JSON value show quotes?
v:type returns a VARIANT, which displays as JSON, so a string shows as "app_open". Cast it with ::VARCHAR (or ::STRING) to get plain text. Cast numbers and timestamps too, before comparing or joining.
Does Snowflake handle Parquet, Avro and XML too?
Yes. Parquet, Avro and ORC load into VARIANT the same way, or straight into columns with MATCH_BY_COLUMN_NAME. XML is supported too, with functions like XMLGET.
🧠 Quick check: JSON in Snowflake
1. How do you read the os field inside device?
2. v:Type returned NULL but v:type works. Why?
3. An events table has 280 rows; 84 checkouts with 171 items in total. How many rows does an (inner) LATERAL FLATTEN on items return?
4. INSERT INTO t VALUES (PARSE_JSON('...')) fails. What works?
5. The app adds a new field to its JSON. What must you change?
Checking your access…