CertSafari
    Databricks Certified Data Engineer Associate· Lessons

    Domain 2 · Lesson 9/33

    Ingesting nested JSON with the VARIANT type and Auto Loader

    Ingest semi-structured and unstructured data (for example, JSON and nested data) via Lakeflow Connect and other managed connectors into Unity Catalog-governed Delta tables

    15 min read
    3% of exam
    5 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Store whole JSON records in a VARIANT column and query nested fields and array elements with path syntax
    • Load JSON into VARIANT with Auto Loader's singleVariantColumn option or with COPY INTO
    • Turn on typed inference for JSON with cloudFiles.inferColumnTypes, and pin individual nested fields with schema hints
    • Pick the schemaEvolutionMode that keeps a JSON stream running and sends unexpected fields to _rescued_data

    Key concept

    VARIANT column — A Delta column type that holds a whole semi-structured record, such as a nested JSON object with its arrays, as one value. You read fields out of it with path expressions when you query, so you don't have to flatten the record or fix a rigid schema when you load it.

    1.Storing a whole JSON record in a VARIANT column

    Nested JSON is a poor fit for a fixed set of columns. Event payloads gain fields, a single key can hold a number in one file and a string in the next, and arrays of objects sit three levels down. You can flatten all of this into a rigid schema when you load it, but every change in the source then becomes a change to your table. The alternative is a VARIANT column. It stores each record whole, and you pull fields out of it when you query. VARIANT is a standard SQL type from Databricks Runtime 15.3 and works in Delta tables. That means it works in Unity Catalog managed tables, which use Delta by default.

    Support depends on the file format. JSON can be ingested as VARIANT from Databricks Runtime 15.3. XML and CSV need 16.4 or later. A table can be a single VARIANT column, CREATE TABLE table_name (variant_column VARIANT). It can also be built with CTAS from a column of JSON strings: PARSE_JSON turns each string into a VARIANT, and a path expression pulls a field out as an ordinary column next to it.

    CTAS that promotes id to its own column and keeps the full record as VARIANTsql
    CREATE TABLE table_name AS
      SELECT json_string:id AS id,
        PARSE_JSON(json_string) variant_column
      FROM source_data

    Pulling id out like this is the recommended pattern. Fields that queries filter or join on most often should become their own non-variant columns, because that speeds up queries and gives better storage layout. There is also a hard reason to do it. A VARIANT column cannot be a clustering key, a partition column or a Z-order key, and the type cannot be used in comparisons, GROUP BY, ORDER BY or set operations. If a dashboard groups by event_type, then event_type has to be a real column.

    Checkpoint 1 of 9· Fill the gap

    This CTAS keeps each full JSON record as a VARIANT and also pulls id out into its own column. Which function completes it?

    CREATE TABLE table_name AS
      SELECT json_string:id AS id,
         ? (json_string) variant_column
      FROM source_data

    Checkpoint 2 of 9· Check yourself

    A Delta table in Unity Catalog stores each JSON event in a VARIANT column called payload. Dashboards filter and group by event_type, a field inside payload. How should you lay out the table so these queries run efficiently?

    Sources1

    2.Querying nested fields with path syntax

    You query a VARIANT with the same path operators used on JSON strings:

    • : selects a top-level field, as in raw:owner.
    • . or ['key'] steps into a nested object, as in raw:store.bicycle.
    • [n] picks an array element by 0-based index, as in raw:store.fruit[0].

    A path that matches nothing returns NULL rather than an error. The same is true of an array index that is out of range.

    Two equivalent ways to reach a nested object inside a VARIANT columnsql
    -- Use dot notation
    SELECT raw:store.bicycle FROM store_data
    
    -- Use brackets
    SELECT raw:store['bicycle'] FROM store_data

    A path into a VARIANT returns another VARIANT. To get a typed value, cast it with ::, for example raw:store.bicycle.price::double. To turn a nested object or array into a struct or array type, use from_json. To unpack an array into one row per element, use variant_explode. It is the VARIANT counterpart of explode, and it outputs pos, key and value columns.

    Checkpoint 3 of 9· Check yourself

    JSON events containing a field named eventType are loaded with Auto Loader into a VARIANT column called payload. An analyst then runs SELECT payload:EventType FROM events. What does the query return?

    Sources234

    3.Loading JSON files straight into VARIANT

    Auto Loader can put each whole file record into one VARIANT column. You do this with the singleVariantColumn option. This holds up well when the source is unpredictable, because nothing about the record's shape has to match a declared schema. The trade-offs are concrete:

    • A malformed record cannot be encoded as VARIANT.
    • A record can be at most 16 MB. Larger records are treated like corrupt records, so in the default PERMISSIVE mode they go to the corrupt record column.
    • The table schema is always the one VARIANT column, so no schema evolution happens and the rescued data column isn't supported.
    Auto Loader writing every JSON record into a single VARIANT columnpython
    (spark.readStream
      .format("cloudFiles")
      .option("cloudFiles.format", "json")
      .option("singleVariantColumn", "variant_column")
      .load("/Volumes/catalog_name/schema_name/volume_name/path")
      .writeStream
      .option("checkpointLocation", checkpoint_path)
      .toTable("table_name")
    )

    You don't have to store the whole record as VARIANT. You can declare a schema in which only some columns are VARIANT, such as name STRING, address VARIANT. You can also pass address VARIANT as a schema hint, and Auto Loader infers every other field with its normal rules. That suits a payload with a stable top level and one deeply nested branch that keeps changing.

    COPY INTO uses the same option for batch loads: singleVariantColumn goes in FORMAT_OPTIONS. COPY INTO is idempotent and skips files it has already loaded (COPY INTO idempotent incremental loads). Where Auto Loader is available, Databricks recommends it over COPY INTO.

    COPY INTO loading JSON files into a one-column VARIANT tablesql
    CREATE TABLE table_name (variant_column VARIANT);
    COPY INTO table_name
      FROM '/Volumes/catalog_name/schema_name/volume_name/path'
      FILEFORMAT = JSON
      FILES = ('file-name')
      FORMAT_OPTIONS ('singleVariantColumn' = 'variant_column')

    Checkpoint 4 of 9· Fill the gap

    The target table has one VARIANT column, and the source JSON changes shape often. Which Auto Loader option makes this stream write each whole record into that column?

    (spark.readStream
      .format("cloudFiles")
      .option("cloudFiles.format", "json")
      .option(" ? ", "variant_column")
      .load("/Volumes/catalog_name/schema_name/volume_name/path")
      .writeStream
      .option("checkpointLocation", checkpoint_path)
      .toTable("table_name")
    )

    Sources1

    4.Typed inference and nested schema hints for JSON

    Often you do want JSON flattened into typed columns. Then you rely on Auto Loader's schema inference, which samples the first files it finds and records the schema at cloudFiles.schemaLocation (Auto Loader schema inference and evolution modes). JSON has one default that surprises people.

    Inferring everything as a string is deliberate. A field read as INT in the sample would cause a type-mismatch failure the first time a later file held "25a" there. If you want numbers, booleans and dates typed from the sample data, as the plain Spark DataFrameReader does, set cloudFiles.inferColumnTypes to true. This option only controls how column types are inferred. It doesn't affect schema evolution, file listing or option validation.

    Sometimes you need one field fixed to a type and want everything else inferred. Schema hints do this. They let you impose the types you know on an inferred schema, and they can reach inside nested data. Use a dot path for struct fields, such as user_info.dob DATE, and .element, .key or .value for arrays and maps, as in the documented hint users.element.id INT. Hints also matter for evolution. addNewColumns is rejected when you pass a full schema with .schema(...), but it works when that schema arrives as a hint.

    Checkpoint 5 of 9· Check yourself

    Your team ingests nested JSON with Auto Loader. They need user_info.dob read as DATE, every other field inferred, and the stream must keep evolving under addNewColumns as new fields appear. Which configuration meets all three needs?

    Checkpoint 6 of 9· Exam question

    During Auto Loader schema inference on a directory of nested JSON files, an engineer notices that every field, including numeric and boolean values, is inferred as a string type in the target Delta table. Which configuration change causes Auto Loader to apply standard Spark type inference (numbers, booleans, dates) to the JSON fields instead of defaulting everything to strings?

    Checkpoint 7 of 9· Exam question

    A data engineer is building an Auto Loader stream that reads deeply nested JSON files. Downstream consumers require that a nested user_info.dob field always be materialized as a DATE column rather than whatever type Auto Loader would otherwise infer for it. Which mechanism lets the engineer force that specific nested field to a chosen type while still letting Auto Loader infer the rest of the schema automatically?

    Sources5

    5.New JSON fields: evolution modes and the rescued data column

    Sooner or later a producer adds a field. Under the default addNewColumns mode, Auto Loader merges the new column onto the end of the schema it has stored and then stops the stream with UnknownFieldException. The stream picks up the new column only after a restart, which is why Databricks recommends running these streams as Lakeflow Jobs that restart automatically. The types of existing columns never change in this mode. Which mode you choose decides whether the stream stops, and whether the new data is kept or lost.

    What each cloudFiles.schemaEvolutionMode does when a JSON file brings a new field
    ModeDoes the stream stop?Where the new field goes
    addNewColumns (default without a provided schema)Yes, with UnknownFieldException. A restart resumes processingAdded as a new column after the restart
    addNewColumnsWithTypeWideningYes, the same as addNewColumnsAdded as a column. Supported widenings such as int to long are applied, and unsupported type changes go to the rescued data column
    rescueNoInto the rescued data column. The schema never evolves
    failOnNewColumnsYes, and it won't restart until you update the schema or remove the fileNowhere. The schema isn't updated
    none (default with a provided schema)NoIgnored, unless the rescuedDataColumn option is set

    rescue is the mode for a stream that must never stop and must not silently drop data. none also keeps the stream running, but without the rescued data column it discards the new fields. Wherever the rescued data column is on, it is the safety net for messy JSON. When Auto Loader infers a schema, it adds the column as _rescued_data. The column catches fields that are missing from the schema, values whose type doesn't match, and keys whose case differs from the schema. Each entry is a JSON blob of the rescued fields plus the source file path of the record. So when a reviewer finds "amount": "n/a" in a DOUBLE column, they can tell which file it came from. Provided schemas and hints are covered in Schema enforcement with provided schemas, schema hints and the rescued data column.

    The rescued column also changes how parser modes treat type mismatches. With rescuedDataColumn set, a mismatch no longer drops the record in DROPMALFORMED mode or raises an error in FAILFAST mode. Only genuinely corrupt JSON fails, for example a truncated object.

    Checkpoint 8 of 9· Match them up

    A producer adds a new field to the JSON files an Auto Loader stream is reading. Match each cloudFiles.schemaEvolutionMode to how the stream handles that file.

    Tap a term, then the definition that fits it.

    Checkpoint 9 of 9· Exam question

    A team continuously lands nested JSON event files in cloud object storage and streams them with Auto Loader into a Unity Catalog-governed Delta table. They want the stream to keep running without interruption when unexpected new fields appear in the JSON payloads, while still capturing those unexpected fields for later review instead of silently dropping them. Which cloudFiles.schemaEvolutionMode setting satisfies this requirement?

    Sources5

    Sources

    (5)

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

    1. 1.
      “VARIANT is a standard SQL type in Databricks Runtime 15.3 and above and is supported by tables backed by Delta Lake.”
      ↩︎ Storing a whole JSON record in a VARIANT column
      “Databricks recommends extracting frequently queried fields and storing them as non-variant columns to accelerate queries and optimize storage layout.”
      ↩︎ Storing a whole JSON record in a VARIANT column
      “The VARIANT data type cannot be used for comparisons, grouping, ordering, and set operations.”
      ↩︎ Storing a whole JSON record in a VARIANT column
      “VARIANT type can only hold records up to 16 MB in size.”
      ↩︎ Loading JSON files straight into VARIANT
      “Malformed records cannot be encoded using VARIANT type.”
      ↩︎ Loading JSON files straight into VARIANT
      “Infers the schema for other fields using standard rules.”
      ↩︎ Loading JSON files straight into VARIANT
      “Databricks recommends using Auto Loader over COPY INTO when available.”
      ↩︎ Loading JSON files straight into VARIANT
      “Because VARIANT is flexible to schema and type changes and maintains case sensitivity and NULL values present in the data source”
      ↩︎ Key concept
      “no schema evolution occurs during ingestion and rescuedDataColumn is not supported”
      ↩︎ Exam trap 1
      “VARIANT columns cannot be used for clustering keys, partitions, or Z-order keys.”
      ↩︎ Exam trap 2
      “VARIANT columns cannot be used for clustering keys, partitions, or Z-order keys.”
      ↩︎ Checkpoint
      “VARIANT is flexible to schema and type changes and maintains case sensitivity and NULL values present in the data source”
      ↩︎ Checkpoint
      “Because the entire record is recorded as a single VARIANT column, no schema evolution occurs during ingestion and rescuedDataColumn is not supported.”
      ↩︎ Prediction
    2. 2.
      “Use . or [<key>] to select nested fields with named keys.”
      ↩︎ Querying nested fields with path syntax
    3. 3.
      “All variant path elements are matched in a case-sensitive way. JSON strings are case-insensitive.”
      ↩︎ Querying nested fields with path syntax
      “The [*] syntax is not support for identifying or unpacking all elements in an array.”
      ↩︎ Querying nested fields with path syntax
      “variant_explode | explode | Outputs pos, key, and value columns.”
      ↩︎ Querying nested fields with path syntax
    4. 4.
      “Use the from_json function to cast nested results into more complex data types, such as arrays or structs.”
      ↩︎ Querying nested fields with path syntax
    5. 5.
      “To enable this behavior with Auto Loader, set the option cloudFiles.inferColumnTypes to true.”
      ↩︎ Typed inference and nested schema hints for JSON
      “You can use schema hints to enforce the schema information that you know and expect on an inferred schema.”
      ↩︎ Typed inference and nested schema hints for JSON
      “addNewColumns is not allowed when the schema of the stream is provided, but does work if you provide your schema as a schema hint.”
      ↩︎ Typed inference and nested schema hints for JSON
      “Auto Loader never evolves the schema and the stream does not fail due to schema changes.”
      ↩︎ New JSON fields: evolution modes and the rescued data column
      “The data types of existing columns remain unchanged.”
      ↩︎ New JSON fields: evolution modes and the rescued data column
      “The rescued data column contains a JSON blob with the rescued columns and the source file path of the record.”
      ↩︎ New JSON fields: evolution modes and the rescued data column
      “When used together with rescuedDataColumn, data type mismatches do not cause Auto Loader to drop records in DROPMALFORMED mode”
      ↩︎ New JSON fields: evolution modes and the rescued data column
      “When Auto Loader detects a new column, the stream stops with an UnknownFieldException.”
      ↩︎ Exam trap 3
      “For formats that don't encode data types (JSON, CSV, and XML), Auto Loader infers all columns as strings (including nested fields in JSON files).”
      ↩︎ Prediction
      “Auto Loader never evolves the schema and the stream does not fail due to schema changes. Auto Loader records all new columns”
      ↩︎ Checkpoint

    Continue to part 2 of 2

    Ingesting unstructured files from SharePoint and Google Drive

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