When you need this
A report built on raw JSON shows empty columns, a count is lower than expected, or a cast fails with Numeric value '...' is not recognized. In most cases the query is fine and the JSON is not what you assumed: a key has different casing, an array is missing on some rows, or a field holds JSON null. This page has the syntax you need and the traps to check first.
Examples use this table:
CREATE OR REPLACE TABLE raw.orders_json (src VARIANT, loaded_at TIMESTAMP_LTZ);
INSERT INTO raw.orders_json
SELECT PARSE_JSON('{
"orderId": 1001,
"Customer": {"id": "C-7", "name": "Acme Ltd", "tier": null},
"createdAt": "2026-11-17T22:41:05Z",
"items": [
{"sku": "A-1", "qty": 2, "price": "19.90"},
{"sku": "B-4", "qty": 1, "price": "5.00"}
]
}'), CURRENT_TIMESTAMP();
Read fields: paths and casts
| Goal | Syntax |
|---|---|
| Top-level field | src:orderId |
| Nested field | src:Customer.name |
| Bracket notation | src['Customer']['name'] |
| Key with spaces or symbols | src:"order id" |
| Array element (0-based) | src:items[0].sku |
| Path from a string | GET_PATH(src, 'Customer.name') |
| Cast to a SQL type | src:orderId::NUMBER, src:Customer.name::STRING |
| Type of a value | TYPEOF(src:items) returns ARRAY, OBJECT, VARCHAR, INTEGER and so on |
| Array length | ARRAY_SIZE(src:items) |
| Keys of an object | OBJECT_KEYS(src:Customer) |
SELECT src:orderId::NUMBER AS order_id,
src:Customer.id::STRING AS customer_id,
src:Customer.name::STRING AS customer_name,
src:createdAt::TIMESTAMP_TZ AS created_at,
ARRAY_SIZE(src:items) AS line_count
FROM raw.orders_json;
Always cast. Without ::STRING the result is still a VARIANT and shows as "Acme Ltd" with quotes, which then fails to join or compare against plain VARCHAR columns the way you expect.
Explode arrays with LATERAL FLATTEN
SELECT o.src:orderId::NUMBER AS order_id,
i.index AS line_no,
i.value:sku::STRING AS sku,
i.value:qty::NUMBER AS qty,
i.value:price::NUMBER(10,2) AS price
FROM raw.orders_json o,
LATERAL FLATTEN(input => o.src:items) i;
FLATTEN returns the columns SEQ, KEY, PATH, INDEX, VALUE and THIS. Use INDEX for array position and KEY when flattening an object.
| Argument | Default | Use |
|---|---|---|
INPUT | required | The VARIANT, OBJECT or ARRAY to expand |
PATH | '' | Path inside INPUT to expand, e.g. PATH => 'items' |
OUTER | FALSE | TRUE keeps one row (with NULL VALUE) when the array is empty or missing |
RECURSIVE | FALSE | TRUE expands every nested level |
MODE | 'BOTH' | 'ARRAY' or 'OBJECT' to limit what is expanded |
Warning
Without
OUTER => TRUE, orders with an empty or missingitemsarray disappear from the result. A fact table built this way silently loses those orders. UseOUTER => TRUEwhenever the parent row must survive.
Nested arrays
Chain a second FLATTEN on the output of the first:
SELECT o.src:orderId::NUMBER AS order_id,
i.value:sku::STRING AS sku,
d.value:code::STRING AS discount_code
FROM raw.orders_json o,
LATERAL FLATTEN(input => o.src:items) i,
LATERAL FLATTEN(input => i.value:discounts, OUTER => TRUE) d;
Discover the shape of unknown JSON
SELECT f.path, TYPEOF(f.value) AS value_type, COUNT(*) AS occurrences
FROM raw.orders_json o,
LATERAL FLATTEN(input => o.src, RECURSIVE => TRUE) f
GROUP BY 1, 2
ORDER BY 1;
Run this on a sample (... FROM raw.orders_json SAMPLE (1000 ROWS) o) before writing a view. It shows casing differences and fields that change type between rows.
The traps
Key names are case-sensitive
The column name is not case-sensitive, but JSON element names are. src:customer.name returns NULL when the key is Customer. There is no error, just empty output.
-- Find which casing the data actually uses
SELECT DISTINCT f.key
FROM raw.orders_json o, LATERAL FLATTEN(input => o.src) f
WHERE LOWER(f.key) = 'customer';
If producers are inconsistent, coalesce both spellings in the view and get the producer fixed.
JSON null is not SQL NULL
A key that is present with value null holds a JSON null, which is a VARIANT value and not SQL NULL. A missing key returns SQL NULL.
| Expression | "tier": null | key missing |
|---|---|---|
src:Customer.tier | JSON null (shows null) | SQL NULL |
src:Customer.tier IS NULL | FALSE | TRUE |
IS_NULL_VALUE(src:Customer.tier) | TRUE | NULL |
src:Customer.tier::STRING | SQL NULL | SQL NULL |
STRIP_NULL_VALUE(src:Customer.tier) | SQL NULL | SQL NULL |
Filters on the raw VARIANT such as WHERE src:Customer.tier IS NULL miss JSON nulls. Cast first (WHERE src:Customer.tier::STRING IS NULL) or use STRIP_NULL_VALUE. To drop null elements at load time, the JSON file format option STRIP_NULL_VALUES = TRUE removes them before they reach the table.
Safe casts
TRY_CAST only accepts string input. Cast the VARIANT to string first, or use a TRY_TO_* function:
SELECT TRY_CAST(i.value:price::STRING AS NUMBER(10,2)) AS price,
TRY_TO_NUMBER(i.value:qty::STRING) AS qty,
TRY_TO_TIMESTAMP_TZ(o.src:createdAt::STRING) AS created_at
FROM raw.orders_json o, LATERAL FLATTEN(input => o.src:items) i;
Find the rows that break a hard cast:
SELECT o.src:orderId, i.value:price
FROM raw.orders_json o, LATERAL FLATTEN(input => o.src:items) i
WHERE i.value:price IS NOT NULL
AND TRY_TO_NUMBER(i.value:price::STRING, 10, 2) IS NULL;
Epoch timestamps
Numbers in seconds or milliseconds need a scale: TO_TIMESTAMP_NTZ(src:ts::NUMBER, 3) for milliseconds, 0 for seconds. Casting a large number straight to a timestamp gives dates far in the future.
Invalid JSON in a string column
PARSE_JSON fails the whole query on one bad row. Use TRY_PARSE_JSON and look at the rows that return NULL:
SELECT raw_text FROM staging.events
WHERE raw_text IS NOT NULL AND TRY_PARSE_JSON(raw_text) IS NULL
LIMIT 20;
Build JSON
| Goal | Function |
|---|---|
| Object from columns, drop SQL NULLs | OBJECT_CONSTRUCT('id', id, 'name', name) |
Object that keeps NULL values as null | OBJECT_CONSTRUCT_KEEP_NULL('id', id, 'tier', tier) |
| Whole row as an object | OBJECT_CONSTRUCT(*) |
| Array from rows | ARRAY_AGG(sku) WITHIN GROUP (ORDER BY sku) |
| Object from key/value rows | OBJECT_AGG(key_col, value_col::VARIANT) |
OBJECT_CONSTRUCT omits a key whose value is SQL NULL. If a consumer expects the key to always be present, use OBJECT_CONSTRUCT_KEEP_NULL.
Loading JSON
CREATE OR REPLACE FILE FORMAT raw.json_ff
TYPE = JSON
STRIP_OUTER_ARRAY = TRUE; -- file is one big [ {...}, {...} ] array
COPY INTO raw.orders_json (src, loaded_at)
FROM (SELECT $1, CURRENT_TIMESTAMP() FROM @raw.orders_stage)
FILE_FORMAT = (FORMAT_NAME = 'raw.json_ff');
Without STRIP_OUTER_ARRAY, a file that is a single top-level array loads as one row and can hit the VARIANT size limit. Check the current limit in the Snowflake documentation; it has been raised over time.
Prevent it next time
- Put a typed view (or a dynamic table) over each raw JSON table, with explicit casts and
OUTER => TRUEwhere parents must survive. Point reports at the view, never atsrc. - Extract fields you filter or join on into real columns at load time. Typed columns are easier to cluster, test and document.
- Run the recursive
FLATTENshape query on new data daily and alert when a new path or a new type appears for an existing path. That is your early warning for upstream schema drift. - Add a data quality check that counts
TRY_TO_*failures per load, so bad values show up as a number instead of a NULL nobody notices.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get