<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sudharsan Ragothaman on Medium]]></title>
        <description><![CDATA[Stories by Sudharsan Ragothaman on Medium]]></description>
        <link>https://medium.com/@sudharsan.nitt?source=rss-fe021898440b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DvqRndgiQftGgTZ7</url>
            <title>Stories by Sudharsan Ragothaman on Medium</title>
            <link>https://medium.com/@sudharsan.nitt?source=rss-fe021898440b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:50:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sudharsan.nitt/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Streamlining JSON Data Integration in Snowflake: A Dynamic Approach]]></title>
            <link>https://medium.com/@sudharsan.nitt/streamlining-json-data-integration-in-snowflake-a-dynamic-approach-89b2270abdb3?source=rss-fe021898440b------2</link>
            <guid isPermaLink="false">https://medium.com/p/89b2270abdb3</guid>
            <dc:creator><![CDATA[Sudharsan Ragothaman]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 21:35:12 GMT</pubDate>
            <atom:updated>2024-03-09T21:35:12.081Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s data-driven landscape, efficient data integration plays a pivotal role in enabling organizations to leverage insights from diverse sources. JSON (JavaScript Object Notation) has emerged as a popular format for exchanging data due to its flexibility and ease of use. Snowflake provides powerful features to handle JSON data seamlessly, allowing organizations to extract, transform, and load (ETL) data with ease.</p><p>Snowflake provides an elegant solution to extract data from json and load it into a snowflake table by offering built-in functions and capabilities for parsing and querying JSON data on the fly. Extracting data from JSON and loading it into Snowflake is a straightforward process that empowers users to seamlessly integrate JSON data into their data workflows. Begin by parsing the JSON data to extract the desired fields and values. Snowflake provides various functions, such as PARSE_JSON, GET, and FLATTEN, to dynamically retrieve key-value pairs from JSON objects. Once the JSON data is parsed, transform it into a structured format suitable for loading into Snowflake. This may involve converting JSON fields into columns and rows, ensuring compatibility with Snowflake’s table structure.</p><p>Before loading the data into Snowflake, create the necessary tables to store the extracted JSON data. Define the table schema based on the fields extracted from the JSON data. Use Snowflake’s data loading tools, such as Snowpipe or the COPY command, to load the transformed JSON data into the corresponding Snowflake tables. Snowflake supports various file formats, including JSON, CSV, and Parquet, making it easy to ingest data from different sources.</p><p>There are lots of resources available online to do the process, Snowflake documentation provides comprehensive guidance, offering clear and concise instructions for every step of the process. I would also highly recommend this well-structured <a href="https://data-engineering-simplified.medium.com/working-with-json-data-in-snowflake-c63965d0710b">article</a> to explore the process.</p><p>The process of extracting data from JSON and loading it into Snowflake, while streamlined, faces a significant challenge when it comes to the creation of tables that align with the structure of the JSON data. This challenge becomes particularly daunting with the presence of complex or large-scale datasets, such as those commonly found in organizational settings. The primary obstacle arises from the need to dynamically create tables in Snowflake with columns that precisely match the key names and hierarchical structure present in the JSON data. Given the semi-structured nature of JSON, this can entail a diverse range of fields with varying levels of nesting, requiring a flexible schema-on-read approach. When dealing with fact tables or extensive datasets, this process can quickly escalate from a simple task to a labor-intensive, time-consuming endeavor.</p><p>At an organizational level, the volume of data being ingested into systems on a daily basis can reach magnitudes of millions of records, each potentially carrying a unique set of key-value pairs. Manually identifying these keys, understanding their data types, and then creating corresponding columns in Snowflake for each new dataset or even for routine updates to existing datasets is not just impractical; it’s nearly impossible. This not only puts a strain on resources but also increases the potential for errors, leading to issues with data integrity and reliability. Another layer of complexity is introduced by the evolving nature of data. In many business environments, the structure of incoming JSON data is subject to change over time. New fields might be added as business requirements evolve, while others may be deprecated. Keeping the Snowflake tables aligned with these dynamic changes requires constant vigilance and regular adjustments to the database schema, a task that is both error-prone and resource-intensive.</p><p>The solution presented tackles the intricate challenge of transforming semi-structured JSON data into a structured table format within Snowflake. The core of this solution leverages the <strong>FLATTEN</strong> function, dynamic SQL, and Snowflake&#39;s ability to pivot data dynamically. This approach aims to automate the creation of tables that align with the varying structures of JSON data, effectively addressing the challenges associated with manual schema mapping and the ingestion of large volumes of data. Here is sample data I chose to work on the solution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*uqqiPCUap88L6ry9otvHKw.png" /></figure><p><strong>Step-by-Step Breakdown of the Solution</strong></p><p><strong>Step 1: Flattening JSON Data</strong></p><p>The first step involves the FLATTEN function, which is pivotal in converting JSON into a tabular format. This function takes JSON objects and arrays and expands them into individual rows, preserving a logical linkage between nested data and its parent. Each flattened record is accompanied by a sequence number (SEQ) for maintaining the order, along with other metadata like the key and value of the JSON element. This process not only simplifies the JSON structure but also makes it accessible for SQL operations.</p><p>Here is the code and output of the sample data for flattening:</p><pre>SELECT * FROM person_address_table t,<br>lateral flatten(input =&gt; t.ADDRESS )f;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*pcyxCcOkKsHTOf0kh-KF1Q.png" /></figure><p><strong>Step 2: Dynamic SQL for Pivoting</strong></p><p>After flattening the JSON, the next challenge is to dynamically transform these key-value pairs into a structured table where each unique key becomes a column. This is where dynamic SQL comes into play. By utilizing the LISTAGG function to aggregate distinct keys and construct a pivot clause, a dynamic SQL statement is formulated. This statement aims to create a new table where the JSON keys are columns, and their associated values are populated accordingly.</p><p>The dynamic SQL statement essentially instructs Snowflake to create a new table and pivot the flattened data such that each unique JSON key becomes a separate column, with the values filled in as the table’s rows. The use of MIN(VALUE) in the pivot operation serves as an aggregation function to ensure compatibility with the pivot operation, even though the primary intent is not to aggregate data but to transpose it.</p><p>For generating the dynamic query using pivot sql query would be something like this:</p><pre>select &#39;select * from (SELECT key,seq,value FROM person_address_table t,<br>lateral flatten(input =&gt; t.ADDRESS )f) pivot (min(VALUE) for KEY in <br>(&#39;||listagg (distinct &#39;&#39;&#39;&#39;||KEY||&#39;&#39;&#39;&#39;, &#39;,&#39;) ||&#39;)) order by id;&#39; <br>from (SELECT key,seq,value FROM person_address_table t, lateral flatten(input =&gt; t.ADDRESS )f);</pre><p>and the output is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*pFa4rpoYVqouXBxyzAz98w.png" /></figure><p><strong>Step 3: Execution and Table Creation</strong></p><p>The dynamic SQL statement is then executed using EXECUTE IMMEDIATE, resulting in the creation of a new table structured as per the JSON keys. This effectively transforms the semi-structured JSON into a structured format, ready for analysis and integration with other data within Snowflake.</p><p>To execute the whole code in an order I created a stored procedure and executed the dynamic SQL</p><pre>CREATE OR REPLACE PROCEDURE json_stored_procedure()<br>RETURNS STRING<br>LANGUAGE SQL<br>AS<br>DECLARE<br>    dynamic_sql STRING;<br>BEGIN<br>    SELECT &#39;CREATE OR REPLACE  TABLE final_table_from_json AS SELECT * FROM (SELECT key,seq,value  FROM person_address_table t,<br>lateral flatten(input =&gt; t.ADDRESS )f) PIVOT (MIN(VALUE) FOR KEY IN (&#39; || LISTAGG(DISTINCT &#39;&#39;&#39;&#39; || KEY || &#39;&#39;&#39;&#39;, &#39;,&#39;) || &#39;)) ORDER BY SEQ  ;&#39;<br>    INTO :dynamic_sql<br>    FROM (SELECT key,seq,value  FROM person_address_table t,<br>lateral flatten(input =&gt; t.ADDRESS )f);<br>   <br>    EXECUTE IMMEDIATE :dynamic_sql;<br>   <br>    RETURN &#39;Done&#39;;<br>END;</pre><p>To call the above stored procedure</p><pre>call json_stored_procedure();</pre><p>To view the final result</p><pre>select * from final_table_from_json;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*hfkjo9uz3B0zbOlXG2MSBA.png" /></figure><p>Alternatively, we can do this without pivoting the table as well with the match case function:</p><pre>SELECT &#39;CREATE OR REPLACE TABLE final_table_from_json AS SELECT&#39; <br>LISTAGG(DISTINCT &#39;MIN(CASE WHEN key = &#39;&#39;&#39; || KEY || &#39;&#39;&#39; THEN value END) AS &#39; || KEY, &#39;, &#39;) <br>|| &#39; FROM (SELECT  f.key, f.value FROM person_address_table t, lateral flatten(input =&gt; t.ADDRESS )f);&#39;<br>INTO :dynamic_sql<br>FROM (SELECT key FROM person_address_table, lateral flatten(input =&gt; ADDRESS));</pre><p>One of the key advantages of this solution is its automation capability. By leveraging dynamic SQL and Snowflake’s pivot functionality, the solution automates the process of schema creation for JSON data. This automation significantly reduces the manual effort required to map JSON structures to Snowflake tables, especially for datasets with complex or frequently changing schemas. As a result, it increases productivity and minimizes the risk of errors that may arise from manual schema mapping.</p><p>Furthermore, the automated nature of the solution enhances scalability. It can seamlessly handle large volumes of JSON data without compromising performance or scalability. Whether dealing with small datasets or massive volumes of data, the solution remains efficient and reliable, allowing organizations to scale their data processing capabilities as needed.</p><p>The solution excels in dynamically adapting to changes in the JSON schema. Snowflake’s pivot functionality, combined with dynamic SQL generation, allows the solution to pivot JSON data into structured tables without requiring prior knowledge of the JSON schema. This capability is crucial for scenarios where the JSON schema is subject to frequent changes or where the structure of incoming JSON data is unpredictable. By dynamically adapting to evolving data schemas, the solution future-proofs data integration processes and reduces the maintenance overhead associated with schema management.</p><p><strong>Conclusion:</strong></p><p>This innovative solution effectively addresses the challenge of dynamically extracting and structuring JSON data within Snowflake, showcasing the platform’s powerful capabilities in handling semi-structured data. By leveraging dynamic SQL and Snowflake’s robust data transformation functions, this approach offers a scalable, flexible method for integrating JSON data into analytical workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89b2270abdb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>