我有一个名为 users 的列,其中包含此 JSON。
{
"[email protected]":[1.0,5.95],
"[email protected]":[2.0,30.733],
"[email protected]":[1.0,4.433],
"[email protected]":[2.0,16.25]
}
我想这样拆开它
我设法使用下面的查询拆分电子邮件,但是我无法获取单独列中的数组值。
select * from tableName
CROSS JOIN UNNEST(SPLIT(array_join(map_keys(CAST(json_parse(users) AS MAP(VARCHAR, JSON))), ', '),','))
AS t (splitUsers)
有办法实现我想要的吗?
你似乎非常接近,选项之一是在未嵌套的值上使用 json 提取函数(例如
json_extract_scalar
):
-- sample data
with dataset (users) as (
values ('{
"[email protected]":[1.0,5.95],
"[email protected]":[2.0,30.733],
"[email protected]":[1.0,4.433],
"[email protected]":[2.0,16.25]
}')
)
-- query
select k splitUsers,
json_extract_scalar(v, '$[0]') firstValue,
json_extract_scalar(v, '$[1]') secondValue
from dataset
, unnest (cast(json_parse(users) as map(varchar, json))) as t(k,v)
;
输出:
您需要首先将地图取消嵌套到单独的行中,然后从 JSON 数组中提取
SELECT
tn.*,
t.splitUsers,
json_extract_scalar(t.vals, '$[0]') AS firstValue,
json_extract_scalar(t.vals, '$[1]') AS secondValue
from tableName AS tn
CROSS JOIN UNNEST(CAST(json_parse(users) AS MAP(VARCHAR, JSON))) AS t (splitUsers, vals);