I have a table (table_1) in snowflake that has 3 columns. The first column is JSON data with arrays within it. Here is an example of one value in the column "JSON":
{
"authors": [
{
"name": "Jim Bob, Jimothy Bob"
}
],
"date": 1578352260,
"publishers": [
{
"name": "Bob Jim"
}
],
"title": "A Look at Ants Through The Ages",
"editors": [
{
"name": "Jim Bobby"
}
]
}
Now, I am trying to unnest and flatten all of this into a new table, but every time I do it just creates a table with 0 rows and 0 data in it. Here is how I am trying to do this:
create or replace table table_2 as
select
json:editors::varchar as editors,
json:authors::varchar as authors,
json:publishers::varchar as publishers,
json:date::varchar as date,
json:title::varchar as title
from table_1,
lateral flatten(input=>json:table_1);
The desired result is
editors authors publishers date title
Jim Bobby Jim Bob Bob Jim 1578352260 A Look at Ants Through The Ages
Jimothy Bob Jim Bob Bob Jim 1578352260 A Look at Ants Through The Ages
The actual result is a successfully created empty table.
How can I flatten out this JSON data?
Thank you for your help.
In your "desired result" I assume you have the editors and authors columns the wrong way round - as in the JSON it is the authors that has two values, not the editors?
However, you can't achieve what you want in pure JSON as you don't actually have two authors: you have a single name field with the value of "Jim Bob, Jimothy Bob". In order to split the data in the way you want the JSON would need to look something like this:
"authors": [
{
"names":{
"name1": "Jim Bob"
"name2": "Jimothy Bob"
}
}
],
In order to achieve what you want you would need to write to a table, splitting the JSON into columns, leaving the value "Jim Bob, Jimothy Bob" in a single column and then split that column (eg using something like SPLIT_TO_TABLE) and join your data together to get the required result
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.