首页 > 解决方案 > Postgresql - 从 [] 值中提取 json 值

问题描述

在 postgresql 中,我试图查询一个视图,其中一个名为codeidsjsonb 的列的类型看起来像这样 - ["Code-oyg0vYNpL", "Code-m9db_s", "Code89nb"]。我想查询这一列,结果每行返回一个值。在上面的示例中,查询应该返回 3 行。

我已经使用json_array_elementsjsonb_array_length提取部分 json 结构对完全形成的 json blob 运行查询。但是有人这个更简单的 json 结构让我感到困惑,因为我无法找出 postgresql 语句提取这三个值的正确格式。提前致谢。

SELECT
  role -> 'title' AS team_role,
  jsonb_array_length(role -> 'names') AS member_count
  FROM jsonb_array_elements(value -> 'team') AS team(role)

标签: sqlarraysjsonpostgresqljsonb

解决方案


你快到了......但你需要在查询中带来实际的表(或视图)。我发现LATERAL JOIN语法在这里更明显:

SELECT
    t.role -> 'title' AS team_role,
    jsonb_array_length(t.role -> 'names') AS member_count
FROM myview v
CROSS JOIN LATERAL jsonb_array_elements(v.codeids -> 'team') AS t(role)

编辑:如果您将 jsonb 数组存储在表列中,那就更简单了:

create table test_table (codeids jsonb);
insert into test_table(codeids) values ('["Code-oyg0vYNpL", "Code-m9db_s", "Code89nb"]');

select x.role
from test_table t
cross join lateral jsonb_array_elements(t.codeids) x(role);

| role           |
| -------------- |
| Code-oyg0vYNpL |
| Code-m9db_s    |
| Code89nb       |

推荐阅读