简体   繁体   English

展平并重构 JSON 雪花

[英]Flatten and reconstruct JSON Snowflake

I am still learning Snowflake, any help would be really appreciated.我仍在学习雪花,任何帮助将不胜感激。

I have a column, let's call it 'result'.我有一个专栏,我们称之为“结果”。

{
  "catalog": [
    {
      "img_href": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179361.jpg",
      "name": "ADITI HAND BLOCKED PRINT",
      "price": 16
    },
    {
      "img_href": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179330.jpg",
      "name": "TORBAY HAND BLOCKED PRINT",
      "price": 17
    },
    {
      "img_href": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179362.jpg",
      "name": "ADITI HAND BLOCKED PRINT",
      "price": 18
    }
  ],
  "datetime": 161878993658
  "catalog_id": 1
}

I would like to flatten it and reconstruct as below我想将其展平并重建如下

[
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179361.jpg"
  },
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179330.jpg"
  },
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179362.jpg"
  },
]

The following will do this.以下将执行此操作。 You won't need the CTE, so delete it and replace uses of tbl with the name of your table and uses of json with your variant column.您将不需要 CTE,因此删除它并将tbl的使用替换为您的表名称,并将json的使用替换为您的变量列。

/*delete this line*/ with tbl as (select parse_json($1) json from values('{"catalog":[{"img_href":"https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179361.jpg","name":"ADITI HAND BLOCKED PRINT","price":16},{"img_href":"https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179330.jpg","name":"TORBAY HAND BLOCKED PRINT","price":17},{"img_href":"https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179362.jpg","name":"ADITI HAND BLOCKED PRINT","price":18}],"datetime":161878993658,"catalog_id":1}'))

select array_agg(new_col) reconstructed
from (
  /* replace json and tbl */ select object_construct('datetime', json:datetime, 'url', obj.value:img_href) new_col, json:catalog_id catalog_id
  from tbl, lateral flatten(json:catalog) obj
) group by catalog_id;

It outputs它输出

[
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179361.jpg"
  },
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179330.jpg"
  },
  {
    "datetime": 161878993658,
    "url": "https://schumacher-webassets.s3.amazonaws.com/Web%20Catalog-600/179362.jpg"
  }
]

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

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