dotConnect for Snowflake Documentation
On this page
    Working with Semi-Structured Data
    On this page

    Snowflake stores semi-structured data, such as JSON documents, in columns of the VARIANT, OBJECT, and ARRAY data types. Learn how to read, query, and modify semi-structured data using dotConnect for Snowflake.

    The examples in this topic use the following table:

    CREATE TABLE EVENTS (ID INT PRIMARY KEY, PAYLOAD VARIANT);
    INSERT INTO EVENTS (ID, PAYLOAD) SELECT 1, PARSE_JSON('{
      "customer": {"name": "Alice", "Order Id": 7},
      "status": "new",
      "nothing": null,
      "items": [{"sku": "A1", "qty": 2}, {"sku": "B2", "qty": 1}]
    }');

    Read Semi-Structured Values

    dotConnect for Snowflake returns VARIANT, OBJECT, and ARRAY values as strings containing JSON text. The GetFieldType method returns System.String, and the GetDataTypeName method returns STRING. When a data adapter populates a DataTable, it creates columns of type System.String for these values.

    The provider preserves the JSON formatting returned by Snowflake. Objects and arrays are indented and span multiple lines. For example, OBJECT_CONSTRUCT('a', 1) returns the following JSON text:

    {
      "a": 1
    }

    To access these values in .NET, parse the JSON text using a library such as System.Text.Json:

    using (SnowflakeCommand command = new SnowflakeCommand("SELECT ID, PAYLOAD FROM EVENTS", connection))
    using (SnowflakeDataReader reader = command.ExecuteReader()) {
      while (reader.Read()) {
        if (reader.IsDBNull(1))
          continue;
        using (JsonDocument document = JsonDocument.Parse(reader.GetString(1))) {
          Console.WriteLine("{0}: {1}", reader.GetInt64(0), document.RootElement.GetProperty("status").GetString());
        }
      }
    }
    
    Using command As New SnowflakeCommand("SELECT ID, PAYLOAD FROM EVENTS", connection)
      Using reader As SnowflakeDataReader = command.ExecuteReader()
        While reader.Read()
          If Not reader.IsDBNull(1) Then
            Using document As JsonDocument = JsonDocument.Parse(reader.GetString(1))
              Console.WriteLine("{0}: {1}", reader.GetInt64(0), document.RootElement.GetProperty("status").GetString())
            End Using
          End If
        End While
      End Using
    End Using
    

    Query Values by Path

    To access individual elements of a semi-structured value, use Snowflake path notation. Separate the column name from the path with a colon, separate field names with periods, and specify array indexes in square brackets. Enclose field names that contain spaces or special characters in double quotation marks. You can also use bracket notation, such as PAYLOAD['status'].

    A path expression returns a VARIANT value, which the provider reads as JSON text. Strings are enclosed in double quotation marks, and numbers are represented as text. To retrieve a typed .NET value, cast the result to an SQL data type using the :: operator:

    SELECT PAYLOAD:customer.name,              -- "Alice"  (String, JSON text)
           PAYLOAD:customer.name::STRING,      -- Alice    (String)
           PAYLOAD:items[0].sku,               -- "A1"     (String, JSON text)
           PAYLOAD:customer."Order Id",        -- 7        (String, JSON text)
           PAYLOAD:items[1].qty::INT           -- 1        (Int64)
    FROM EVENTS WHERE ID = 1

    You can use path expressions and command parameters in the same SQL statement, even if a field and a parameter have the same name. The provider sends the statement to Snowflake as is, and Snowflake distinguishes them: PAYLOAD:status identifies a field, whereas :status identifies a parameter:

    SELECT ID FROM EVENTS WHERE PAYLOAD:status::STRING = :status

    SQL NULL and JSON null

    If a field doesn't exist, the path expression returns SQL NULL, which the provider reads as DBNull. If a field contains JSON null, the provider returns the string null. If you cast the result with ::STRING, both cases return SQL NULL. To determine whether a field contains JSON null, use the IS_NULL_VALUE function.

    Expand Arrays Using FLATTEN

    To return each element of an array as a separate row, use the FLATTEN table function:

    SELECT e.ID, f.INDEX, f.VALUE:sku::STRING AS SKU, f.VALUE:qty::INT AS QTY
    FROM EVENTS e, LATERAL FLATTEN(INPUT => e.PAYLOAD:items) f
    ORDER BY e.ID, f.INDEX

    The query returns two rows, one for each element of the items array:

    ID

    INDEX

    SKU

    QTY

    10A12
    11B21

    Write Semi-Structured Values

    Snowflake doesn't accept parameters of the Variant, Object, and Array types. A statement with such a parameter fails with an error such as "Unsupported data type 'VARIANT'". A String parameter can't be inserted into a VARIANT, OBJECT, or ARRAY column directly either, because Snowflake doesn't convert text to these types. Such a statement fails with the "Expression type does not match column data type, expecting VARIANT but got VARCHAR" error. To write semi-structured data, pass JSON text as a String parameter and convert it using the PARSE_JSON function in the SQL statement. In the SET clause of an UPDATE statement, Snowflake converts JSON text implicitly, but use PARSE_JSON there as well to make the conversion explicit.

    To insert semi-structured values, use INSERT ... SELECT. Snowflake doesn't support PARSE_JSON in the VALUES clause of an INSERT statement. For example, INSERT ... VALUES (PARSE_JSON(:payload)) results in the "Invalid expression [PARSE_JSON(:payload)] in VALUES clause" error. To update an existing value, use PARSE_JSON in the SET clause of an UPDATE statement.

    string json = "{\"customer\":{\"name\":\"Alice\"},\"status\":\"new\"}";
    
    // INSERT: PARSE_JSON isn't allowed in VALUES, so use INSERT ... SELECT
    using (SnowflakeCommand command = new SnowflakeCommand(
        "INSERT INTO EVENTS (ID, PAYLOAD) SELECT :id, PARSE_JSON(:payload)", connection)) {
      command.Parameters.Add("id", DbType.Int64).Value = 2;
      command.Parameters.Add("payload", DbType.String).Value = json;
      command.ExecuteNonQuery();
    }
    
    // UPDATE: PARSE_JSON can be used in SET
    using (SnowflakeCommand command = new SnowflakeCommand(
        "UPDATE EVENTS SET PAYLOAD = PARSE_JSON(:payload) WHERE ID = :id", connection)) {
      command.Parameters.Add("payload", DbType.String).Value = "{\"status\":\"done\"}";
      command.Parameters.Add("id", DbType.Int64).Value = 2;
      command.ExecuteNonQuery();
    }
    
    Dim json As String = "{""customer"":{""name"":""Alice""},""status"":""new""}"
    
    ' INSERT: PARSE_JSON isn't allowed in VALUES, so use INSERT ... SELECT
    Using command As New SnowflakeCommand( _
        "INSERT INTO EVENTS (ID, PAYLOAD) SELECT :id, PARSE_JSON(:payload)", connection)
      command.Parameters.Add("id", DbType.Int64).Value = 2
      command.Parameters.Add("payload", DbType.String).Value = json
      command.ExecuteNonQuery()
    End Using
    
    ' UPDATE: PARSE_JSON can be used in SET
    Using command As New SnowflakeCommand( _
        "UPDATE EVENTS SET PAYLOAD = PARSE_JSON(:payload) WHERE ID = :id", connection)
      command.Parameters.Add("payload", DbType.String).Value = "{""status"":""done""}"
      command.Parameters.Add("id", DbType.Int64).Value = 2
      command.ExecuteNonQuery()
    End Using
    

    You can also construct semi-structured values from scalar parameters using the OBJECT_CONSTRUCT and ARRAY_CONSTRUCT functions. To modify a field in an existing object, use OBJECT_INSERT:

    INSERT INTO EVENTS (ID, PAYLOAD) SELECT :id, OBJECT_CONSTRUCT('status', :status, 'tags', ARRAY_CONSTRUCT(:tag1, :tag2));
    UPDATE EVENTS SET PAYLOAD = OBJECT_INSERT(PAYLOAD, 'status', :status, TRUE) WHERE ID = :id;

    Update Semi-Structured Data Using a Data Adapter

    When a data adapter populates a DataTable, it reads VARIANT, OBJECT, and ARRAY values as JSON text.

    To insert or update these values, define custom InsertCommand and UpdateCommand commands that convert the JSON text using PARSE_JSON. The commands generated by SnowflakeCommandBuilder use parameters of the Variant type for modified semi-structured values, which results in the "Unsupported data type 'VARIANT'" error.

    The following example defines custom commands and updates a semi-structured value in a DataTable:

    SnowflakeDataAdapter adapter = new SnowflakeDataAdapter("SELECT ID, PAYLOAD FROM EVENTS", connection);
    
    SnowflakeCommand update = new SnowflakeCommand(
        "UPDATE EVENTS SET PAYLOAD = PARSE_JSON(:payload) WHERE ID = :id", connection);
    update.Parameters.Add("payload", DbType.String, 0, "PAYLOAD");
    update.Parameters.Add("id", DbType.Int64, 0, "ID");
    adapter.UpdateCommand = update;
    
    SnowflakeCommand insert = new SnowflakeCommand(
        "INSERT INTO EVENTS (ID, PAYLOAD) SELECT :id, PARSE_JSON(:payload)", connection);
    insert.Parameters.Add("id", DbType.Int64, 0, "ID");
    insert.Parameters.Add("payload", DbType.String, 0, "PAYLOAD");
    adapter.InsertCommand = insert;
    
    DataTable table = new DataTable();
    adapter.Fill(table);
    table.Rows[0]["PAYLOAD"] = "{\"status\":\"updated\"}";
    adapter.Update(table);
    
    Dim adapter As New SnowflakeDataAdapter("SELECT ID, PAYLOAD FROM EVENTS", connection)
    
    Dim update As New SnowflakeCommand( _
        "UPDATE EVENTS SET PAYLOAD = PARSE_JSON(:payload) WHERE ID = :id", connection)
    update.Parameters.Add("payload", DbType.String, 0, "PAYLOAD")
    update.Parameters.Add("id", DbType.Int64, 0, "ID")
    adapter.UpdateCommand = update
    
    Dim insert As New SnowflakeCommand( _
        "INSERT INTO EVENTS (ID, PAYLOAD) SELECT :id, PARSE_JSON(:payload)", connection)
    insert.Parameters.Add("id", DbType.Int64, 0, "ID")
    insert.Parameters.Add("payload", DbType.String, 0, "PAYLOAD")
    adapter.InsertCommand = insert
    
    Dim table As New DataTable()
    adapter.Fill(table)
    table.Rows(0)("PAYLOAD") = "{""status"":""updated""}"
    adapter.Update(table)
    

    For more information about data type mapping, see Data Type Mapping. For more information about updating data, see Updating Data.