如何在presto db中扩展字典列表
How to expand a list of dict in presto db
我在 prestodb 中有一列是字典列表:
[{"id": 45238, "kind": "product", "name": "Ball", "category": "toy"}, {"id": 117852, "kind": "service", "name": "courier", "category": "transport"}]
有没有办法扩展此列以获得如下内容:
id kind name category
4528 product Ball toy
117852 service courier transport
有时密钥可能与上面的示例不同,也可能比上面的 4 个密钥更多
我正在尝试:
with cte as ( select cast(divs as json) as json_field from table)
select m['id'] id,
m['kind'] kind,
m['name'] name,
m['category'] category
from cte
cross join unnest(cast(json_field as array(map(varchar, json)))) as t(m)
错误:
INVALID_CAST_ARGUMENT: Cannot cast to array(map(varchar, json)). Expected a json array, but got [{"id": 36112, "kind"....
假设您的数据包含 json - 您可以将其转换为从 varchar 到 json (array(map(varchar, json))
) 的映射数组,然后使用 unnest
来展平数组:
WITH dataset (json_str) AS (
VALUES (json '[{"id": 45238, "kind": "product", "name": "Ball", "category": "toy"}, {"id": 117852, "kind": "service", "name": "courier", "category": "transport"}]')
)
select m['id'] id,
m['kind'] kind,
m['name'] name,
m['category'] category
from dataset
cross join unnest(cast(json_str as array(map(varchar, json)))) as t(m)
id
kind
name
category
45238
product
Ball
toy
117852
service
courier
transport
UPD
如果原始列类型是 varchar - 使用 json_parse
将其转换为 json。
我在 prestodb 中有一列是字典列表:
[{"id": 45238, "kind": "product", "name": "Ball", "category": "toy"}, {"id": 117852, "kind": "service", "name": "courier", "category": "transport"}]
有没有办法扩展此列以获得如下内容:
id kind name category
4528 product Ball toy
117852 service courier transport
有时密钥可能与上面的示例不同,也可能比上面的 4 个密钥更多
我正在尝试:
with cte as ( select cast(divs as json) as json_field from table)
select m['id'] id,
m['kind'] kind,
m['name'] name,
m['category'] category
from cte
cross join unnest(cast(json_field as array(map(varchar, json)))) as t(m)
错误:
INVALID_CAST_ARGUMENT: Cannot cast to array(map(varchar, json)). Expected a json array, but got [{"id": 36112, "kind"....
假设您的数据包含 json - 您可以将其转换为从 varchar 到 json (array(map(varchar, json))
) 的映射数组,然后使用 unnest
来展平数组:
WITH dataset (json_str) AS (
VALUES (json '[{"id": 45238, "kind": "product", "name": "Ball", "category": "toy"}, {"id": 117852, "kind": "service", "name": "courier", "category": "transport"}]')
)
select m['id'] id,
m['kind'] kind,
m['name'] name,
m['category'] category
from dataset
cross join unnest(cast(json_str as array(map(varchar, json)))) as t(m)
id | kind | name | category |
---|---|---|---|
45238 | product | Ball | toy |
117852 | service | courier | transport |
UPD
如果原始列类型是 varchar - 使用 json_parse
将其转换为 json。