[英]Extract values from a JSON Array in Presto
I have a column with JSON arrays like below:我有一列 JSON arrays 如下所示:
{data=[{"name":"col1","min":0,"max":32,"avg":29},
{"name":"col2","min":1,"max":35,"avg":21},
{"name":"col3","min":4,"max":56,"avg":34}]}
I'm trying to parse the array and extract specific values based on conditions.我正在尝试解析数组并根据条件提取特定值。 For example
例如
value of "min"
where "name"="col1"
: 0 "min"
的值,其中"name"="col1"
:0
value of "avg"
where "name"="col3"
: 34 "avg"
的值,其中"name"="col3"
:34
Does anyone have a solution for that?有没有人有解决方案?
Your JSON is not valid one.您的 JSON 无效。 it should be
{"data":[
not {data = [
它应该是
{"data":[
不是{data = [
If JSON is valid (you can easily fix it in subquery), extract data, cast it to array(row) and get values using CASE conditional statements.如果 JSON 有效(您可以在子查询中轻松修复它),提取数据,将其转换为数组(行)并使用 CASE 条件语句获取值。 I added max() aggregation here to remove NULL records and get all required values in single row, you can use filter instead (for example
where x.name = 'col1'
), depending on what you need:我在此处添加了 max() 聚合以删除 NULL 记录并在单行中获取所有必需的值,您可以使用 filter 代替(例如
where x.name = 'col1'
),具体取决于您的需要:
with mydata as (
select '{"data":[{"name":"col1","min":0,"max":32,"avg":29},
{"name":"col2","min":1,"max":35,"avg":21},
{"name":"col3","min":4,"max":56,"avg":34}]}' json
)
select max(case when x.name = 'col1' then x.min end) min_col1,
max(case when x.name = 'col3' then x.avg end) avg_col3
from mydata
CROSS JOIN
UNNEST(
CAST(
JSON_EXTRACT(json,'$.data')
as ARRAY(ROW(name VARCHAR, min INTEGER, max INTEGER, avg INTEGER))
)
) as x(name, min, max, avg) --column aliases
Result:结果:
min_col1 avg_col3
0 34
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.