简体   繁体   English

Postgresql - 从 [] 值中提取 json 值

[英]Postgresql - Extract values from json from [] values

In postgresql I am trying to query a view where one column called codeids is of type jsonb that looks like this - ["Code-oyg0vYNpL", "Code-m9db_s", "Code89nb"] .在 postgresql 中,我试图查询一个视图,其中一个名为codeids列是codeids类型,看起来像这样 - ["Code-oyg0vYNpL", "Code-m9db_s", "Code89nb"] I want to query this column with the results being returned one value per line.我想查询这一列,结果每行返回一个值。 In the example above the query should return 3 lines.在上面的例子中,查询应该返回 3 行。

I have run queries on fully formed json blobs using json_array_elements and jsonb_array_length to extract parts of the json structure.我已经使用json_array_elementsjsonb_array_length对完全形成的 json blob 运行查询以提取部分 json 结构。 But someone this simpler json structure is confusing me as I can't figure out the right format for postgresql statement to extract these three values.但是有人这个更简单的 json 结构让我感到困惑,因为我无法找出用于提取这三个值的 postgresql 语句的正确格式。 Thanks in advance.提前致谢。

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

You are almost there... but you need to bring the actual table (or view) in the query.你快到了……但是你需要在查询中引入实际的表(或视图)。 I find that the LATERAL JOIN syntax makes it more obvious here:我发现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)

Edit : if you are storing the jsonb array in a table column, that's a bit simpler:编辑:如果您将 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       |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM