【问题标题】:How to get value from a JSON array column using Redshift?如何使用 Redshift 从 JSON 数组列中获取值?
【发布时间】:2021-05-17 21:55:49
【问题描述】:

背景

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

[{"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 非常陌生,并且只完成了基本的查询。

【问题讨论】:

  • @Serge 谢谢。我厌倦了您的建议,但出现以下错误:语法错误:数据库:prod-redshift (Amazon Redshift) at or near "select"

标签: json amazon-redshift


【解决方案1】:

尽管 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;

【讨论】:

    【解决方案2】:

    你建立一个表和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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多