简体   繁体   English

在雪花/SQL 中从 JSON 数据子 arrays 创建表

[英]Creating a table from JSON data sub arrays within in snowflake/SQL

I have a table (table_1) in snowflake that has 3 columns.我在雪花中有一个表(table_1),它有 3 列。 The first column is JSON data with arrays within it.第一列是 JSON 数据,其中包含 arrays。 Here is an example of one value in the column "JSON":以下是“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.现在,我正在尝试将所有这些取消嵌套并将其展平到一个新表中,但每次我这样做只是创建一个包含 0 行和 0 个数据的表。 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?我怎样才能弄平这个 JSON 数据?

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?在您的“期望结果”中,我假设您的编辑和作者列的方式错误 - 如在 JSON 中,作者有两个值,而不是编辑?

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".但是,您无法在纯 JSON 中实现您想要的,因为您实际上没有两个作者:您只有一个名称字段,其值为“Jim Bob,Jimothy Bob”。 In order to split the data in the way you want the JSON would need to look something like this:为了以您想要的方式拆分数据,JSON 需要看起来像这样:

"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为了实现您想要的内容,您需要写入表,将 JSON 拆分为列,将值“Jim Bob,Jimothy Bob”留在单个列中,然后拆分该列(例如使用 SPLIT_TO_TABLE 之类的东西)并加入您的数据一起获得所需的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM