![](/img/trans.png)
[英]Query to extract ids from a deeply nested json array object in Presto
[英]Extract complex nested JSON array in Presto
我有一個像這樣的復雜 JSON 對象:
{
"item_detail": [
{
"itemid": "4702385896",
"modelid": "8307307322",
"quantity": "1"
},
{
"itemid": "3902478595",
"modelid": "8306561848",
"quantity": "1"
},
{
"itemid": "3409528897",
"modelid": "10922686275",
"quantity": "1"
},
{
"itemid": "4702385896",
"modelid": "8307307323",
"quantity": "1"
}
],
"shopid": "128449080"
},
{
"item_detail": [
{
"itemid": "7906381345",
"modelid": "9745718882",
"quantity": "1"
},
{
"itemid": "6710792892",
"modelid": "11474621623",
"quantity": "1"
}
],
"shopid": "36121097"
}
]
我正在努力將所有(itemid、shopid)提取到 Presto 中的行中。 我想要的結果是:
itemid | shopid
-----------+-------
4702385896 | 128449080
3902478595 | 128449080
3409528897 | 128449080
4702385896 | 128449080
7906381345 | 36121097
6710792892 | 36121097
我已經使用 CROSS JOIN UNNEST 和 TRANSFORM 來獲得結果,但沒有運氣。 有沒有人對此有解決方案?
非常感謝!
將json_extract
與cast
to array
和unnest
,如下所示:
presto:default> SELECT
-> json_extract_scalar(item_detail, '$.itemid') itemid,
-> json_extract_scalar(shopping, '$.shopid') shopid
-> FROM t
-> CROSS JOIN UNNEST(CAST(my_json AS array(json))) AS x(shopping)
-> CROSS JOIN UNNEST(CAST(json_extract(shopping, '$.item_detail') AS array(json))) AS y(item_detail)
-> ;
->
itemid | shopid
------------+-----------
4702385896 | 128449080
3902478595 | 128449080
3409528897 | 128449080
4702385896 | 128449080
7906381345 | 36121097
6710792892 | 36121097
(6 rows)
(在 Presto 327 上驗證)
順便說一句,如果任何數組可能為空或丟失,我建議使用LEFT JOIN UNNEST ... ON true
而不是CROSS JOIN UNNEST
(這需要一個像樣的 Presto 版本):
SELECT
json_extract_scalar(item_detail, '$.itemid') itemid,
json_extract_scalar(shopping, '$.shopid') shopid
FROM t
LEFT JOIN UNNEST(CAST(my_json AS array(json))) AS x(shopping) ON true
LEFT JOIN UNNEST(CAST(json_extract(shopping, '$.item_detail') AS array(json))) AS y(item_detail) ON true;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.