What you will be able to do
- Explain how VARIANT, OBJECT and ARRAY nest to hold semi-structured data, and turn JSON text into a VARIANT with PARSE_JSON
- Choose between PARSE_JSON and TRY_PARSE_JSON for malformed input, and explain why TO_JSON does not round-trip the original text exactly
- Reach nested values with colon, dot and bracket paths, respect key case sensitivity, and cast path results to typed columns
- Expand arrays and objects into rows with LATERAL FLATTEN and choose the right INPUT, PATH, OUTER and RECURSIVE settings
- Read XML loaded into a VARIANT using $, @, @attribute and XMLGET
Key concept
VARIANT — VARIANT is Snowflake's universal container type: it can hold a value of any type, including OBJECT and ARRAY values whose own elements are VARIANTs, so a whole JSON, Parquet or XML hierarchy fits in one column and stays queryable.
1.Parsing JSON into VARIANT, OBJECT and ARRAY
Semi-structured data does not have a fixed schema. A JSON feed can add a new attribute tomorrow, two records in the same batch can carry different keys, and any value can contain a further object or array. A relational table with fixed columns can't absorb that, so Snowflake stores this data in three types built for it. An OBJECT is a set of key-value pairs (a dictionary or map). An ARRAY is an ordered list. A VARIANT can hold anything, including an OBJECT or an ARRAY.
These types nest because the relationship goes both ways: a VARIANT can wrap an OBJECT or ARRAY, and every value inside an OBJECT or ARRAY is itself a VARIANT. So an ARRAY of OBJECTs, each of which holds another ARRAY, is a legal value of any depth. When you load JSON, Avro, ORC or Parquet, Snowflake builds this hierarchy for you and converts it to an optimized internal format that SQL can query efficiently.
JSON reaches a VARIANT in one of two ways. For staged files, you create a table with a VARIANT column and run COPY INTO with FILE_FORMAT = (TYPE = 'JSON'). For JSON that already sits in a string, such as a VARCHAR column or a literal, you call PARSE_JSON, which interprets the string as a JSON document and returns a VARIANT. The input can be at most 64 MB compressed.
INSERT INTO vartab
SELECT column1 AS n, PARSE_JSON(column2) AS v
FROM VALUES (1, 'null'),
(2, null),
(3, 'true'),
(4, '-17'),
(5, '123.12'),
(6, '1.912e2'),
(7, '"Om ara pa ca na dhih" '),
(8, '[-1, 12, 289, 2188, false,]'),
(9, '{ "x" : "abc", "y" : false, "z": 10} ')
AS vals;| Input string | TYPEOF of the VARIANT | Why |
|---|---|---|
| 'null' | NULL_VALUE | A JSON null, which is a real value and not SQL NULL |
| null (SQL NULL) | NULL | SQL NULL in gives SQL NULL out |
| '-17' | INTEGER | Whole number |
| '123.12' | DECIMAL | Decimals are kept exact as fixed-point numbers |
| '1.912e2' | DOUBLE | Scientific notation is stored as DOUBLE |
| '[-1, 12, ...]' | ARRAY | Square brackets |
| '{ "x" : "abc", ... }' | OBJECT | Curly braces |
Three edge cases can trip a pipeline. An empty or whitespace-only string returns NULL instead of an error, so a batch with blank rows keeps loading. Duplicate keys are rejected by default with Error parsing JSON: duplicate object attribute. Passing 'd' as the second argument allows them, and only the last value for the key survives. JSON has no date, timestamp or binary types, so those values arrive as strings, and you cast them when you extract them.
Malformed text is where the two parsing functions part ways. PARSE_JSON raises an error on a string it can't parse, as the duplicate-key case shows, and the statement stops there. TRY_PARSE_JSON parses the same way but returns NULL when parsing fails, so a truncated webhook payload lands as a NULL row you can count and inspect after the load. Pick PARSE_JSON when bad input should halt the job, and TRY_PARSE_JSON when it should be set aside. Either way, TYPEOF(v) shows what each parsed value turned into.
TO_JSON runs the other way, turning a VARIANT back into a JSON string, but the round trip is not exact. The key order in its output is not predictable and whitespace can shrink, so TO_JSON(PARSE_JSON('{"b":1,"a":2}')) need not equal the text that went in. To test whether two documents hold the same data, compare the parsed VARIANT values rather than the re-serialized strings.
Checkpoint 1 of 7· Fill the gap
column2 holds JSON documents stored as text strings, and the target column v is a VARIANT. Which function completes this INSERT so that each string is interpreted as JSON and stored as a VARIANT value?
INSERT INTO vartab
SELECT column1 AS n, ? (column2) AS v
FROM VALUES (1, 'null'),
(2, null),
(3, 'true'),
(4, '-17'),
(5, '123.12'),
(6, '1.912e2'),
(7, '"Om ara pa ca na dhih" '),
(8, '[-1, 12, 289, 2188, false,]'),
(9, '{ "x" : "abc", "y" : false, "z": 10} ')
AS vals;PARSE_JSON reads a string as a JSON document and returns a VARIANT. That is how JSON already held in a VARCHAR or a literal reaches a VARIANT column. TO_JSON goes the other way and turns a VARIANT into a string. PARSE_XML is for XML text, and TO_VARCHAR returns a string, not a VARIANT.
Source: docs.snowflake.comCheckpoint 2 of 7· Check yourself
A nightly job parses a VARCHAR column of webhook payloads, and a few payloads arrive truncated. The team wants the INSERT to finish and the broken payloads to land as NULL for later review. Which function should the INSERT call?
TRY_PARSE_JSON returns NULL when a string can't be parsed, so the load continues. PARSE_JSON returns NULL only for empty or whitespace-only strings and raises an error on malformed JSON, the 'd' argument only permits duplicate keys, and TO_JSON converts a VARIANT to a string.
“A special version of PARSE_JSON that returns a NULL value if an error occurs during parsing.”Source: docs.snowflake.com
2.Reaching nested values with colon, dot and bracket paths
A colon after the column name steps into the first level of a VARIANT, and each later level uses a dot. In src:salesperson.name, src is the column, salesperson is a top-level key, and name is a key inside it. Bracket notation gets the same value, src['salesperson']['name'], with the key names in single quotes. Array elements are reached by a 0-based index in square brackets, so src:vehicle[0].make reads the make of the first vehicle.
SELECT src:salesperson.name
FROM car_sales
ORDER BY 1;Case matters for key names but not for column names. src:salesperson.name and SRC:salesperson.name are the same path, but SRC:Salesperson.Name is a different one. The reason is that JSON keys follow JSON's own rules for strings, not Snowflake's rules for SQL identifiers, so nothing that folds identifier case applies to them. A key spelled with the wrong case doesn't raise an error. It just matches nothing, and the expression returns NULL on every row. That makes it easy to miss in a dashboard, because the query runs fine and the columns come back empty.
Keys that are not valid SQL identifiers must be put in double quotes in the path. Examples include a key with a space (src:"company name"), a key that starts with a digit (zipcode_info:"94987") and a key that starts with a symbol (measurements:"#sPerSquareInch"). You can also quote ordinary keys if you like.
Every path expression returns a VARIANT, which is why results such as "Frank Beasley" appear in double quotes. For a consumable column, add :: to the end of the path: src:salesperson.name::STRING returns a VARCHAR, and src:vehicle[0].price::NUMBER returns a number. The cast works directly on the VARIANT, so there is no need to convert to text first. The rules for conversion failures and the TRY_ variants are in Casting and TRY_ conversion.
Checkpoint 3 of 7· Check yourself
In car_sales the JSON stores the keys exactly as salesperson and name. A colleague edits the dashboard path src:salesperson.name. Which edit makes the query return NULL on every row instead of the salesperson names?
Element names are case-sensitive, so Salesperson and Name match nothing and the path quietly returns NULL. The column name ignores case, and bracket notation or double-quoted keys are just other spellings of the same lowercase path.
“Regardless of which notation you use, the column name is case-insensitive but element names are case-sensitive.”Source: docs.snowflake.com
Checkpoint 4 of 7· Exam question
A raw_events table stores JSON in a VARIANT column named raw. Documents are stored as {"UserId":42,"Country":"NL"}. A dashboard query SELECT raw:userid::NUMBER, raw:country::STRING FROM raw_events returns NULL for every row, although the data is present. What explains this and fixes it?
Correct answer: C — Key names in path notation are case-sensitive, so the query must use the stored spelling and read raw:UserId and raw:Country with the casts
- A. Snowflake keeps the key casing exactly as it was in the JSON document and does not lowercase anything at load time. Quoting a lowercase key would still fail to match the stored UserId key.
- B. That parameter affects how quoted SQL identifiers such as column names are resolved. It has no effect on key names inside a VARIANT, which are always matched case-sensitively.
- C. Correct. Element names after the colon are matched case-sensitively against the document, so userid and country find nothing and return NULL. Using the exact casing UserId and Country returns the values.
- D. VARIANT values can be cast directly with the double-colon operator, which is the standard way to type extracted elements. The NULLs come from the key mismatch, not from the casts.
Sources4
3.Turning arrays into rows with LATERAL FLATTEN
A path can reach one element of an array, but analysts usually need one row per element: one row per item on an order, or per customer on a sale. FLATTEN does this. It is a table function that takes a VARIANT, OBJECT or ARRAY and returns one row per element. With LATERAL in the FROM clause it becomes a correlated view: each source row is joined to its own expanded elements, and the source row's columns are repeated on every row it produces.
SELECT
value:name::string as "Customer Name",
value:address::string as "Address"
FROM
car_sales
, LATERAL FLATTEN(INPUT => SRC:customer);INPUT should point at the array you want to expand, not the document that contains it. For an orders row with payload = {"customer":"Ana","items":[...]}, FLATTEN(input => o.payload:items) gives one row per item, and i.value:sku::STRING reads each item's field. Writing FLATTEN(input => o.payload) expands the outer object, which gives one row per top-level key (customer, items), because MODE defaults to BOTH. On those rows value:sku is NULL. Skipping FLATTEN and writing o.payload:items:sku doesn't work either, because items is an array and the path never chooses an element.
| Column | What it holds |
|---|---|
| SEQ | A sequence number for the input record, not guaranteed to be gap-free or ordered |
| KEY | For objects, the key of the exploded value; NULL for array elements |
| PATH | The path to the element, such as b[0] |
| INDEX | The element's position if the input is an array; otherwise NULL |
| VALUE | The element itself, as a VARIANT you can path into and cast |
| THIS | The element being flattened, useful when flattening recursively |
Four optional arguments change what comes out:
PATHnames an element inside INPUT to expand.FLATTEN(INPUT => PARSE_JSON('{"a":1, "b":[77,88]}'), PATH => 'b')returns two rows, with pathsb[0]andb[1]. It is a location, not a filter: a PATH that doesn't exist in the input, such as'sku'on an order payload whose sku keys sit inside an array, produces no rows.OUTER => TRUEkeeps rows whose expansion is empty. By default, a source row whose array is empty, or whose path can't be found, disappears from the output, much like an inner join. With OUTER set, that row appears once with NULL in KEY, INDEX and VALUE.RECURSIVE => TRUEexpands every sub-element at every depth, not only the referenced level. It is the standard way to list every key and path in an unfamiliar document.MODElimits expansion to'OBJECT','ARRAY'or'BOTH'(the default).
Arrays nested inside arrays need chained FLATTEN calls. In car_sales, each vehicle has an extras array, so the query flattens SRC:vehicle as vm and then flattens vm.value:extras as ve. That returns one row per extra per car. The second FLATTEN can reference vm only because of LATERAL. For a single-level array, TABLE(FLATTEN(...)) and LATERAL FLATTEN(...) return the same result.
Checkpoint 5 of 7· Check yourself
In car_sales, each sale's vehicle key holds an array of vehicles, and each vehicle carries its own extras array. You need exactly one output row per extra per car. Which FROM clause produces that?
extras is an array inside each element of the vehicle array, so you need two FLATTEN calls. The first expands vehicle, and the second expands each vehicle's extras. The second call can use vm only because of LATERAL. Flattening vehicle alone gives one row per car with the whole extras array in it. Flattening SRC gives one row per top-level key, where value:extras is NULL. SRC:vehicle.extras never picks an array element, so there is nothing to expand.
“{"make": "Honda", "model": "Civic", "year": "2017", "price": "20275", "extras":["ext warranty", "paint protection"]}”Source: docs.snowflake.com
Checkpoint 6 of 7· Exam question
An orders table has columns order_id NUMBER and payload VARIANT. Each payload looks like {"customer":"Ana","items":[{"sku":"A1","qty":2},{"sku":"B7","qty":1}]}. An analyst needs one output row per purchased item with order_id, sku, and qty. Which query does this?
Correct answer: B — SELECT o.order_id, i.value:sku::STRING AS sku, i.value:qty::NUMBER AS qty FROM orders o, LATERAL FLATTEN(input => o.payload:items) i
- A. Restricting FLATTEN to the path 'sku' looks for a key named sku at the top of the document, where none exists, so no rows come back. The array of items is never expanded, which makes this unusable.
- B. Correct. LATERAL FLATTEN on the items array emits one row per element, and the VALUE column holds each item object so sku and qty can be extracted and cast. Each output row stays correlated with its parent order_id.
- C. This still reads sku and qty from the whole items array instead of from the flattened element. Path notation cannot reach into an array without an index, so the extracted columns come back NULL.
- D. Flattening the whole payload yields one row per top-level key, namely customer and items. The VALUE column then holds a string or the array, so sku and qty resolve to NULL.
Sources5
4.Reading XML with $, @ and XMLGET
XML lands in a VARIANT the same way JSON does. A staged file loads with FILE_FORMAT=(TYPE=XML) into a VARIANT column, and an XML string becomes an OBJECT through PARSE_XML. XML elements carry two kinds of data, content between the tags and attributes on the opening tag, so Snowflake reads them with two operators of their own rather than keys.
COPY INTO sample_xml_parts FROM @~/xml_stage FILE_FORMAT=(TYPE=XML) ON_ERROR='CONTINUE';$ returns an element's contents, and @ returns its name. If the element contains text, $ gives that text. If it contains one child element, you get that element. If it contains a series of children, you get an array of them. @ alone gives the tag name, so src:"@" on the parts document returns "parts". @ followed by a name gives that attribute's value, and NULL if the attribute is absent. Combining them, src:"$"[0]."@count" reads the count attribute of the first <part>, which is 4.
XMLGET(expr, 'tag', n) finds a child element by name. The instance number is 0-based and defaults to 0, so XMLGET(src, 'part', 3) is the fourth <part>. It returns the whole element (opening tag, content and closing tag) as an OBJECT, not the text inside it. To get text, add :"$". To get an attribute, use GET(tag, '@attrname') or the path form XMLGET(x, 'price'):"@currency". XMLGET returns NULL when the tag isn't found. It also does not work on a VARCHAR, even one holding valid XML, so run text through PARSE_XML first.
SELECT XMLGET(VALUE, 'item'):"$"::VARCHAR AS item,
XMLGET(VALUE, 'partnum'):"$"::VARCHAR AS partnum,
COALESCE(XMLGET(VALUE, 'manufacturer'):"$"::VARCHAR,
XMLGET(VALUE, 'source'):"$"::VARCHAR) AS manufacturer_or_source,
XMLGET(VALUE, 'price'):"$"::VARCHAR AS price,
FROM sample_xml_parts,
LATERAL FLATTEN(INPUT => SRC:"$");Some part elements have a manufacturer child and others have a source child instead. XMLGET returns NULL for a tag that isn't present, so COALESCE picks whichever one exists for each part.
Checkpoint 7 of 7· Check yourself
Each part element in sample_xml_parts has a price child with a units attribute set to dollar and an amount such as 27.00 as its text. In the LATERAL FLATTEN query over SRC:"$", which select expression returns only the price amount for each part, not the whole element and not the currency?
XMLGET returns the whole price element as an OBJECT, so casting it directly gives you the tag and its markup, not the amount. Adding :"$" reads the element's contents, which here is the price text. :"@units" reads the units attribute (dollar), and :"@" on its own returns the tag name (price).
“$ for the contents of the value.”Source: docs.snowflake.com
Sources
(7)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“An ARRAY or OBJECT holds a value of type VARIANT.”
↩︎ Parsing JSON into VARIANT, OBJECT and ARRAY“a data type that can hold a value of any other data type (including ARRAY and OBJECT)”
↩︎ Key concept - 2.
“Interprets an input string as a JSON document, producing a VARIANT value.”
↩︎ Parsing JSON into VARIANT, OBJECT and ARRAY“the returned object has a single instance of that key with the last value specified for that key”
↩︎ Parsing JSON into VARIANT, OBJECT and ARRAY“treating 123.45 as NUMBER(5,2), not as a DOUBLE value”
↩︎ Parsing JSON into VARIANT, OBJECT and ARRAY“The order of the key-value pairs in the string produced by TO_JSON is not predictable.”
↩︎ Parsing JSON into VARIANT, OBJECT and ARRAY“An error is returned because duplicate keys aren’t allowed by default”
↩︎ Parsing JSON into VARIANT, OBJECT and ARRAY“if the input string is 'null', then it is interpreted as a JSON null value”
↩︎ Prediction - 3.
“A special version of PARSE_JSON that returns a NULL value if an error occurs during parsing.”
↩︎ Parsing JSON into VARIANT, OBJECT and ARRAY“A special version of PARSE_JSON that returns a NULL value if an error occurs during parsing.”
↩︎ Exam trap 4 - 4.
“the column name is case-insensitive but element names are case-sensitive”
↩︎ Reaching nested values with colon, dot and bracket paths“The rules for JSON keys (element names) are different from the rules for Snowflake SQL identifiers.”
↩︎ Reaching nested values with colon, dot and bracket paths“the query output is enclosed in double quotes because the query output is VARIANT, not VARCHAR.”
↩︎ Reaching nested values with colon, dot and bracket paths“the column name is case-insensitive but element names are case-sensitive”
↩︎ Exam trap 1“Regardless of which notation you use, the column name is case-insensitive but element names are case-sensitive.”
↩︎ Checkpoint“{"make": "Honda", "model": "Civic", "year": "2017", "price": "20275", "extras":["ext warranty", "paint protection"]}”
↩︎ Checkpoint - 5.
“If TRUE, exactly one row is generated for zero-row expansions (with NULL in the KEY, INDEX, and VALUE columns).”
↩︎ Turning arrays into rows with LATERAL FLATTEN“If TRUE, the expansion is performed for all sub-elements recursively.”
↩︎ Turning arrays into rows with LATERAL FLATTEN“use LATERAL so that each subsequent FLATTEN can reference the output of the previous one.”
↩︎ Turning arrays into rows with LATERAL FLATTEN“the values in this input row are replicated to match the number of rows produced by FLATTEN.”
↩︎ Turning arrays into rows with LATERAL FLATTEN“The path to the element within a VARIANT data structure that needs to be flattened.”
↩︎ Exam trap 2 - 6.
“Use @attribute_name for the contents of a named attribute.”
↩︎ Reading XML with $, @ and XMLGET“If no attribute is found, NULL is returned.”
↩︎ Reading XML with $, @ and XMLGET“$ for the contents of the value.”
↩︎ Checkpoint - 7.
“Like an array index, the instance_number is 0-based, not 1-based.”
↩︎ Reading XML with $, @ and XMLGET“The XMLGET function does not operate directly on a VARCHAR expression even if that VARCHAR contains valid XML text.”
↩︎ Reading XML with $, @ and XMLGET“but the entire element (the opening tag, content, and closing tag)”
↩︎ Exam trap 3