presto 如何判断数组中是否存在 json 字段?

问题描述 投票:0回答:1

如果我有一个包含 json 对象列表的字段

jsonCol
,例如:

[{'name': 'fieldA', 'enum': 'someValA'},
 {'name': 'fieldB', 'enum': 'someValB'},
 {'name': 'fieldC', 'enum': 'someValC'}]

另一行可能看起来像:

[{'name': 'fieldA', 'enum': 'someValA'},
 {'name': 'fieldC', 'enum': 'someValC'}]

如何获取存在

fieldB
的行? 我有一个查询可以查找
fieldB
的值,但是在
fieldB
不存在的情况下查询失败并出现错误:

Error running query: Array subscript must be less than or equal to array length: 1 > 0

我的查询:

SELECT
    json_extract_scalar(filter(cast(json_parse(jsonCol) AS array(json)), x -> json_extract_scalar(x, '$.name') = 'fieldB')[1], '$.enum') AS myField
FROM myTable
WHERE
    json_extract_scalar(filter(cast(json_parse(jsonCol) AS array(json)), x -> json_extract_scalar(x, '$.name') = 'fieldB')[1], '$.enum') = 'someValB'

如何检查

someValB
的值,同时忽略 json 根本不存在的情况?

sql arrays json presto redash
1个回答
0
投票

你可以这样做:

json_each()
用于返回每个数组元素或对象成员的行。

json_extract()
从 json 对象中提取并返回一个或多个值。

with cte as (
  select key, value, json_extract(value,'$.name') as name, json_extract(value,'$.enum') as enum
  from myTable, json_each(jsonCol)
)
select enum
from cte
where name = 'fieldB';

结果:

enum
someValB

这里演示

© www.soinside.com 2019 - 2024. All rights reserved.