[英]JSON Parsing in Snowflake - Square Brackets At Start
我正在嘗試解析雪花中的一些 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",
也許您可以使用兩個橫向展平來處理 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" |
+-----------------------------+
這些方括號表示您的FULLFILLMENTS
字段中有一組 JSON 對象。 除非確實需要在一個字段中STRIP_OUTER_ARRAY
對象,否則您應該查看COPY
命令的STRIP_OUTER_ARRAY
屬性。 一個例子可以發現這里的雪花文件中:
copy into <table>
from @~/<file>.json
file_format = (type = 'JSON' strip_outer_array = true);
如果其他人遇到相同的數據問題(一個陣列中的所有 json 數據),我有這個解決方案:
select f.VALUE:fulfillment_service::string
from TEST_WEEK,
lateral flatten( FULFILLMENTS[0].line_items ) f;
有了這個,你只需抓住數組的第一個元素(這是唯一的元素)。
如果您有嵌套數組元素,只需將其添加到橫向展平:
, RECURSIVE => TRUE, mode => 'array'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.