背景
我有一个表,其中一列包含如下所示的数据:
[{"category": "Sports & Outdoors", "rank": 218, "link": "www.foop.com"},{"category": "Bike Saddle Covers", "rank": 1, "link" : "www.foo2.com"}]
据我了解,上面是一个json数组。我尝试 select json_array_length(col_1) from mytable
并且能够返回长度 2,所以我知道它是一个 json 数组。
问题
我希望从数组内的每个 json 中提取键 category
的值。
我不确定如何继续。我知道,如果它是一个简单的 json,我可以执行类似 select col_name -> 'category' from table
的操作。
我尝试过的
`select array_to_json(col_1) from mytable`
错误:函数 array_to_json(字符变化)不存在
我还尝试了从 mytable 中选择 array_to_json(col_1::varchar)
如果我能在这里得到任何帮助,我将不胜感激,因为我对 sql 非常陌生,并且只完成了基本查询。
最佳答案
尽管 Redshift 基于 Postgres,但它是 different in some parts .
JSON functions Redshift 非常有限。我可以想象,使用这些功能来完成您的任务的唯一可能的解决方案是:
select
json_extract_path_text(
json_extract_array_element_text(col_1, 0),
'category')
from mutable
union
select
json_extract_path_text(
json_extract_array_element_text(col_1, 1),
'category')
from mutable;
结果
如果您有复杂的 JSON 结构或 JSON 数组中有许多元素,那么这肯定不是一个可扩展的解决方案。
使用 null_if_invalid
参数可以在一定程度上有所帮助
select
json_extract_path_text(
json_extract_array_element_text(col_1, 0),
'category'
)
from mutable
union
select
json_extract_path_text(
json_extract_array_element_text(col_1, 1, true),
'category', true)
from mutable
union
select
json_extract_path_text(
json_extract_array_element_text(col_1, 2, true),
'category', true)
from mutable
union
select
json_extract_path_text(
json_extract_array_element_text(col_1, 3, true),
'category', true)
from mutable;
关于json - 如何使用 Redshift 从 JSON 数组列获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67577521/