CertSafari
    Snowflake SnowPro Advanced: Data Analyst (DAA-C01)· Lessons

    Domain 2 · Lesson 8/19

    Querying JSON and XML in VARIANT columns

    Prepare different data types into a consumable format.

    16 min read
    4.6% of exam
    7 sources
    Published 20 Oct 2026
    Docs as of 18 Oct 2026

    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.

    PARSE_JSON turning strings of different shapes into VARIANT valuessql
    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;
    What TYPEOF reports for each value parsed above
    Input stringTYPEOF of the VARIANTWhy
    'null'NULL_VALUEA JSON null, which is a real value and not SQL NULL
    null (SQL NULL)NULLSQL NULL in gives SQL NULL out
    '-17'INTEGERWhole number
    '123.12'DECIMALDecimals are kept exact as fixed-point numbers
    '1.912e2'DOUBLEScientific notation is stored as DOUBLE
    '[-1, 12, ...]'ARRAYSquare brackets
    '{ "x" : "abc", ... }'OBJECTCurly 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;

    Checkpoint 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?

    Sources123

    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.

    Dot notation from a VARIANT column down two levelssql
    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?

    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?

    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.

    One row per customer, with each element read through VALUE and cast to textsql
    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.

    The fixed set of columns every FLATTEN row returns
    ColumnWhat it holds
    SEQA sequence number for the input record, not guaranteed to be gap-free or ordered
    KEYFor objects, the key of the exploded value; NULL for array elements
    PATHThe path to the element, such as b[0]
    INDEXThe element's position if the input is an array; otherwise NULL
    VALUEThe element itself, as a VARIANT you can path into and cast
    THISThe element being flattened, useful when flattening recursively

    Four optional arguments change what comes out:

    • PATH names an element inside INPUT to expand. FLATTEN(INPUT => PARSE_JSON('{"a":1, "b":[77,88]}'), PATH => 'b') returns two rows, with paths b[0] and b[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 => TRUE keeps 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 => TRUE expands 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.
    • MODE limits 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?

    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?

    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.

    Loading a staged XML document into a VARIANT columnsql
    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.

    FLATTEN over the root's children, then XMLGET plus $ to pull each child's textsql
    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:"$");

    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?

    Sources67

    Sources

    (7)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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. 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. 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. 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. 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. 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. 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

    Continue to part 2 of 2

    CSV and Parquet file formats for loading into Snowflake

    Spotted a mistake, or was something unclear? Tell us.