在Presto SQL查询中提取JSON数据

laximzn5  于 2022-11-26  发布在  Presto
关注(0)|答案(1)|浏览(562)

我在我的表中有3列。ID、受理人、注解注解列是json格式,如下所示
[{“作者”:“a”,“时间戳”:“2022-11- 22 T21:43:51 Z”},{“作者”:“B”,“时间戳”:“2022年11月22日22:56:03 Z”},............]
我尝试从表中提取数据,但得到NULL值。
我尝试了以下查询:

SELECT 
    assignee, 
    ID,
    CAST(json_extract(comments,'$.comments') AS ARRAY<MAP<VARCHAR, VARCHAR>>) 
    AS ticket_commenters_with_timestamp 
  FROM 
    table1

它在最后一列中给出NULL。
我期待以下结果:
ID.受分配人.作者.时间戳
1.

Andrew.        a.           2022-08-17T14:01:16Z
Andrew.        b.           2022-08-17T14:01:18Z

有没有人能帮助我,让我知道我做错了什么?提前谢谢

bis0qfac

bis0qfac1#

您的json不是json对象,它是json数组,并且它确实有comments属性,您需要将它作为json数组处理,如果您想扁平化它,使用unnest,例如:

-- sample data
WITH dataset(assignee, ID, comments) AS (
 values ('Andrew', 1, json '[{"author": "a", "timestamp": "2022-08-17T14:01:16Z"}, {"author": "b", "timestamp": "2022-08-17T14:01:18Z"}]')
)

-- query
select ID,
    assignee,
    json_extract(m, '$.author') as author,
    json_extract(m, '$.timestamp') as timestamp
from dataset,
unnest(cast(comments as array(json))) as t(m);

输出量:
| 识别码|受让人|作者|时间戳记|
| - -|- -|- -|- -|
| 一个|安德鲁|一种|2022年8月17日星期三14时01分16秒|
| 一个|安德鲁|B| 2022年8月17日星期一14时01分18秒|
附言
如果comments列是varchar而不是json,则使用json_parse

相关问题