【问题标题】:Unnest json string array未嵌套的 json 字符串数组
【发布时间】:2019-12-10 15:40:57
【问题描述】:

我正在使用 psql,我有一个如下所示的表:

id | dashboard_settings
-----------------------
 1 | {"query": {"year_end": 2018, "year_start": 2015, "category": ["123"]}}

有很多行,但对于每一行,“类别”值是一个包含一个整数的数组(字符串格式)。

有没有办法可以“解包”类别对象?所以它只有 123 作为整数?

我试过了,但没有成功:

SELECT jsonb_extract_path_text(dashboard_settings->'query', 'category') from table

这会返回:

jsonb_extract_path_text | ["123"]

当我想要的时候:

jsonb_extract_path_text | 123

【问题讨论】:

    标签: sql arrays json postgresql


    【解决方案1】:

    您需要使用数组访问运算符,它只是 ->> 后跟数组索引:

    select jsonb_extract_path(dashboard_settings->'query', 'category') ->> 0
    from the_table
    

    或者:

    select dashboard_settings -> 'query' -> 'category' ->> 0
    from the_table
    

    【讨论】:

      【解决方案2】:

      考虑:

      select dashboard_settings->'query'->'category'->>0 c from mytable
      

      Demo on DB Fiddle

      | c | | :-- | | 123 |

      【讨论】:

        猜你喜欢
        • 2020-02-16
        • 1970-01-01
        • 2020-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多