Discover the power of Snowflake's lateral flatten function in exploding multiple JSON values within nested JSON lists!

I have a variant table containing 24 JSONs that look like the following (one per row):

{
  "context": "marketplace",
  "metadata": {
    "app_version": "1.0.4 (166)",
  },
  "params": {
    "filter": {
      "brands": [],
      "categories": [
        "f28c7c9f-09ae-4218-821a-bec344998289"
      ],
      "manufacturers": [],
      "page": 1,
      "product_name": "",
    },
    "page": "product_list",
    "results": 3
  },
  "user_id": "6443a2db-4526-4fc5-8084-290fc78e5336"
}

My goal is to explode everything into individual rows. Currently, I have managed to achieve this for everything except the "filter" section using the following code:

SELECT data:event::string,
       data:user_id::string,
       data:metadata.app_version::string,
       data:context::string,
       data:params.page::string,
       data:params.filter.page::string,
       data:params.results::string
FROM ods.stg_tanimis_events

The lists "brands," "categories," and "manufacturers" can be empty, but I would like a null value if that is the case. Ideally, I would like to have table columns for:

event, user_id, app_version, context, param_page, filter_page, results, manufacturer, brand, category

I have attempted several lateral flatten queries without success:

select * FROM table
, lateral flatten (data:params:filter:categories) j2;

select * FROM table
, lateral flatten (data:params:filter.brands) j1

select * FROM table
, lateral flatten (data:params:filter:brands) j1
, lateral flatten (data:params:filter:categories) j2;

select user_id, filter, flat.*
from table
, lateral flatten(parse_json(filter)) flat;


WITH j as (
SELECT *
FROM table
, lateral flatten(data:params:filter))

SELECT *
from j,
lateral flatten (j.value) j2;

Unfortunately, these queries return either 8 rows or 0 rows, or they throw errors. Is there a solution to achieve the desired result? Thank you.

Answer №1

In this specific dataset, the "brands" section is empty, which means that performing a flatten operation on it won't yield any results unless you include ", OUTER => TRUE" in your lateral flatten statement. Here's an updated version of the query:

SELECT table.data:event::string,
   table.data:user_id::string,
   table.data:metadata.app_version::string,
   table.data:context::string,
   table.data:params.page::string,
   table.data:params.filter.page::string,
   table.data:params.results::string,
   j1.value::string as brands,
   j2.value::string as categories
FROM table
, lateral flatten (data:params:filter:brands, OUTER => TRUE) j1
, lateral flatten (data:params:filter:categories, OUTER => TRUE) j2;

By using ", OUTER => TRUE", this query will function similar to a LEFT JOIN operation, returning NULL for any flattened arrays that are empty.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Gson in Kotlin to Parse JSON with Nested Objects

I am attempting to transform the JSON below into a list data object: [ { "type": "PHOTO", "id": "pic1", "title": "Photo 1", "dataMap": {} }, { "type": ...

Tips for modifying the JSON format within a Spring and Angular project

I am utilizing Spring for the backend and Angular for the frontend. Below is my REST code: @GetMapping(path = "/endpoint") public @ResponseBody Iterable<Relations> getGraphGivenEndpointId(@RequestParam(value = "id") int id) { return ...

Updating array properties in a JSON object using a foreach loop will automatically update all corresponding keys

Having a slight headache working on this particular issue. My aim is to construct an array of JSON objects using a foreach loop, and everything is functioning perfectly except for one property. The problematic property is actually an array that gets update ...

Is it possible for JSON deserialization to fail within a Controller action, yet succeed when performed explicitly?

Seeking clarification on a matter that has puzzled me. While my controller actions usually handle JSON deserialization to C# objects smoothly, there is currently an issue I am grappling with. Instead of producing the expected outcome, it presents a QBWebho ...

Utilizing AJAX to retrieve and process JSON information

Hey there! I've been diving into the world of creating AJAX calls to PHP scripts lately. Trying to figure out the best solution to handle these AJAX calls, you can check out my client-side code in this question. I'm here to validate my underst ...

Extracting information from an API

Hey there, good morning! I'm currently working on gathering car data from this website: My process involves sending a request through the search bar on the homepage for a specific location and date. This generates a page like this: From there, I us ...

Attempting to manipulate arrays by using the json_query method

I'm experiencing difficulties with using the json_query function to filter arrays based on a specific key value. When providing the direct path, this is the API result that is displayed: ok: [localhost] => { "msg": [ { ...

Struggling to make JavaScript read JSON data from an HTML file

I am currently working on developing a word search game using django. One of the tasks I need to accomplish is checking whether the entered word exists in a dictionary. To achieve this, I have been converting a python dictionary into JSON format with json. ...

Having trouble converting a JSON array into a JavaScript array upon creation

I have encountered this question multiple times before and despite trying various solutions, I have not been able to find success. Summary: My goal is to retrieve the array from the classes.json file and then assign the data in the variable classes from d ...

Converting an object with a System.Drawing.Image into a json format

I'm facing a bit of a challenge and struggling to find a solution... Within my interface (and implemented class), there is an image property... Guid uid { get; set; } Image imageData1 { get; set; } string fileName { get; set; } The imag ...

Leverage the power of rxjs to categorize and organize JSON data within an

I am in need of reformatting my data to work with nested ngFor loops. My desired format is as follows: this.groupedCities = [ { label: 'Germany', value: 'de', items: [ {label: 'Berlin', value: 'Berlin ...

The connection to the Docker Container on localhost is not established

I am currently working on setting up a React app that communicates with a json server within a docker container. Below is the Dockerfile configuration I am using: # base image FROM node:alpine # set working directory WORKDIR '/app' # add `/app ...

DataTables: Reordering array elements while rendering

When utilizing DataTables with server-side processing, I encounter a json object that contains an array of LocalDateTime elements: ... "SimpleDate": [ 2000,12,31,0,0 ] ... In the initialization script, my columns definition is as follows: "columns": [ ...

Can you provide examples of iterating through multiple maps with key-value pairs using ng-repeat in AngularJS?

Within my controller, the data is structured like so: "type": [ { "aMap": {"5.0": 0}, "bMap": {"10.0": 0}, "cMap": {"15.0": 0}, "dMap": {"20.0": 0}, "desc": "CG" }, { "aMap": {"5.0": 0}, ...

What is the process for transforming the result of a .aspx file into a JSON format?

I am trying to convert the output of an .aspx page into a JSON object in order to accommodate a JSONP Ajax request. Here is what's happening on the page: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="mypage.aspx.cs" Inherits="folder_myp ...

Sending data from TextBox as json format

JavaScript Code: var latitude = document.getElementById("<%=txt_Lat.ClientID %>").value; var longitude = document.getElementById("<%=txt_Long.ClientID %>").value; var jsonData = {latitude: latitude, longitude: longitude}; var jsonString = JSO ...

Is there a way to develop a nested JSON web service using C#?

I am working on displaying a list of products with their product names and group ids using a webservice with different levels. For Level 0, the display should contain the group id with the product names as child levels. So far, I have created two diction ...

Using JSON Serialization in MVC3

How do I handle JSON serialization for the object being returned as null in my controller? public class CertRollupViewModel { public IEnumerable<CertRollup> CertRollups { get; set; } } public class CertRollup { public decimal TotalCpm { get ...

"Unraveling the mysteries of deserializing JSON with unfamiliar

Perhaps this may not be achievable. Check out the functioning code below: HttpResponseMessage playerResponse = await client.GetAsync("2018/export?TYPE=players&DETAILS=1&SINCE=&PLAYERS=9988%2C13604&JSON=1"); if (playerResponse.IsSuccessSta ...

Navigating the nuances of working with nullable and non-nullable types using generics

Developing a specialized LookupConverter : JsonConverter class was essential for efficient JSON serialization and deserialization of ILookup objects. Given the complexities arising from dealing with generics and the lack of a public concrete Lookup class, ...