[英]Parsing nested JSON fields in Snowflake
我是 Snowflake 的新手,我現在正在嘗試解析 JSON 字段並提取其屬性以在響應中返回。
我嘗試了一些變體,但每次都將屬性填充為null
。
我表中的attributes
列有這個 JSON :
{
"Status": [
"ACTIVE"
],
"Coverence": [
{
"Sub": [
{
"EndDate": [
"2020-06-22"
],
"Source": [
"Test"
],
"Id": [
"CovId1"
],
"Type": [
"CovType1"
],
"StartDate": [
"2019-06-22"
],
"Status": [
"ACTIVE"
]
}
]
}
]
}
我試過的:
SELECT DISTINCT *
from
(
TRIM(mt."attributes":Status, '[""]')::string as STATUS,
TRIM(r.value:"Sub"."Id", '[""]')::string as ID,
TRIM(r.value:"Sub"."Source", '[""]')::string as SOURCE
from "myTable" mt,
lateral flatten ( input => mt."attributes":"Coverence", outer => true) r
)
GROUP BY
STATUS,
ID,
SOURCE;
后來我試過:
SELECT DISTINCT *
from
(
TRIM(mt."attributes":Status, '[""]')::string as STATUS,
TRIM(r.value:"Id", '[""]')::string as ID,
TRIM(r.value:"Source", '[""]')::string as SOURCE
from "myTable" mt,
lateral flatten ( input => mt."attributes":"Coverence":"Sub", outer => true) r
)
GROUP BY
STATUS,
ID,
SOURCE;
但沒有任何效果。 STATUS
正在按預期填充。 但是ID
和SOURCE
正在填充null
。
我錯過了什么或者我做了一些愚蠢的事情嗎? 請說明一下。
假設Coverence
可以包含多個Sub
,因此 FLATTEN 兩次。 在最低級別,僅選擇第一個元素( EndDate[0]
、 Source[0]
等):
SELECT
mt."attributes":Status[0]::TEXT AS Status
,r2.value:EndDate[0]::TEXT AS EndDate
,r2.value:Source[0]::TEXT AS Source
,r2.value:Id[0]::TEXT AS Id
FROM myTable AS mt,
LATERAL FLATTEN(input => mt."attributes",
path => 'Coverence',
outer => true) r1,
LATERAL FLATTEN(input => r1.value,
path => 'Sub',
outer => true) r2;
Output:
你所有的元素都是數組類型,整體 JSON 沒有多大意義......所以要訪問你所有的單個元素,你必須使用 [] 表示法然后你可以訪問元素值。 如果您只需要通過索引訪問單個元素,則也不需要使用 flatten。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.