雪花中的JSON解析-开始时用方括号

时间:2020-09-25 03:01:08

标签: sql json snowflake-cloud-data-platform

我正在尝试解析雪花中的一些JSON文件。在这种情况下,我想从具有“ fulfillment_service”:“ gift_card”的行中提取“礼品卡”。我已经成功查询了一维JSON数据,但这-用方括号括起来-让我感到困惑。

这是我的简单查询-我创建了一个名为“ TEST_WEEK”的小表

select line_items:fulfillment_service
from TEST_WEEK
, lateral flatten(FULFILLMENTS:line_items) line_items;

希望这不是一个太基本的问题。我对解析JSON非常了解。

谢谢!

这是FULLFILLMENTS字段的开头,其中包含我想获取的信息。

[
  {
    "admin_graphql_api_id": "gid://shopify/Fulfillment/2191015870515",
    "created_at": "2020-08-10T14:54:38Z",
    "id": 2191015870515,
    "line_items": [
      {
        "admin_graphql_api_id": "gid://shopify/LineItem/5050604355635",
        "discount_allocations": [],
        "fulfillable_quantity": 0,
        "fulfillment_service": "gift_card",
        "fulfillment_status": "fulfilled",
        "gift_card": true,
        "grams": 0,
        "id": 5050604355635,
        "name": "Gift Card - $100.00",
        "origin_location": {
          "address1": "100 Indian Road",
          "address2": "",
          "city": "Toronto",
          "country_code": "CA",

2 个答案:

答案 0 :(得分:3)

也许您可以使用两个横向展平来处理line_items数组中的值:

样品表:

create table TEST_WEEK( FULFILLMENTS variant ) as
select parse_json(
'[
  {
    "admin_graphql_api_id": "gid://shopify/Fulfillment/2191015870515",
    "created_at": "2020-08-10T14:54:38Z",
    "id": 2191015870515,
    "line_items": [
      {
        "admin_graphql_api_id": "gid://shopify/LineItem/5050604355635",
        "discount_allocations": [],
        "fulfillable_quantity": 0,
        "fulfillment_service": "gift_card",
        "fulfillment_status": "fulfilled",
        "gift_card": true,
        "grams": 0,
        "id": 5050604355635,
        "name": "Gift Card - $100.00",
        "origin_location": {
          "address1": "100 Indian Road",
          "address2": "",
          "city": "Toronto",
          "country_code": "CA"
      }
      }
      ]
  }
]');

示例查询:

select s.VALUE:fulfillment_service 
from TEST_WEEK, 
lateral flatten( FULFILLMENTS ) f,
lateral flatten( f.VALUE:line_items ) s;

输出:

+-----------------------------+
| S.VALUE:FULFILLMENT_SERVICE |
+-----------------------------+
| "gift_card"                 |
+-----------------------------+

答案 1 :(得分:0)

那些方括号表示您的FULLFILLMENTS字段中有一个JSON对象数组。除非确实需要在一个字段中包含对象数组,否则应查看STRIP_OUTER_ARRAY命令的COPY属性。可以在Snowflake文档中找到here的示例:

copy into <table>
from @~/<file>.json
file_format = (type = 'JSON' strip_outer_array = true);