如何使用 Redshift 从 JSON 数组列中获取值?

How to get value from a JSON array column using Redshift?

背景

我有一个 table,其中一列包含如下所示的数据:

[{"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`

错误function array_to_json(character varying) does not exist

我也试过了select array_to_json(col_1::varchar) from mytable

我很感激这里的任何帮助,因为我是 sql 的新手并且只做过基本查询。

您构建了 table 和 json 数组的连接

SELECT arr.item ->> 'category'
FROM myTable, json_array_elements(col1) arr(item) 

这里的 arr(item) 是任意符号,允许我们引用 json 数组的各个元素。这是该案例的教程

https://levelup.gitconnected.com/working-with-a-jsonb-array-of-objects-in-postgresql-d2b7e7f4db87

尽管 Redshift 基于 Postgres,但它是 different in some parts

JSON functions 的红移非常有限。我能想到的使用这些功能完成任务的唯一可能解决方案是:

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;