Postgres从jsonb数组中提取值

时间:2017-02-09 11:52:27

标签: postgresql postgresql-9.4 jsonb

我有一个jsonb字段,其数组如下所示:

[  
   {  
      "type":"discount",
      "title":"Discount 10%"
   },
   {        
      "file":"zx5rP8EoacyfhqGndcSOnP8VYtkr9Ya8Nvf7oYL98YDsM1CLMYIurYvfVUU4AGkzBsovwssT0bq.pdf",
      "type":"menu",
      "title":"Some menu title etc"
   }
]

如果数组中有 type = menu ,我想获取文件属性。

我设法做的是知道是否有,但我怎样才能最终提取文件值?

case when offers @> '[{"type":"menu"}]' then true else false end

我不想在下面做这样的事情,因为数组可能不包含折扣类型。

offers->1->'file'

2 个答案:

答案 0 :(得分:1)

使用jsob_array_elements()->>运算符(请参阅JSON Functions and Operators。)

with a_table(json_col) as (
values (
'[  
   {  
      "type":"discount",
      "title":"Discount 10%"
   },
   {        
      "file":"zx5rP8EoacyfhqGndcSOnP8VYtkr9Ya8Nvf7oYL98YDsM1CLMYIurYvfVUU4AGkzBsovwssT0bq.pdf",
      "type":"menu",
      "title":"Some menu title etc"
   }
]'::jsonb)
)

select value->>'file' as filename
from a_table,
lateral jsonb_array_elements(json_col)
where value->>'type' = 'menu'

                                    filename                                     
---------------------------------------------------------------------------------
 zx5rP8EoacyfhqGndcSOnP8VYtkr9Ya8Nvf7oYL98YDsM1CLMYIurYvfVUU4AGkzBsovwssT0bq.pdf
(1 row)

答案 1 :(得分:1)

例如:

t=# with a as (with v as (select '[
   {
      "type":"discount",
      "title":"Discount 10%"
   },
   {
      "file":"zx5rP8EoacyfhqGndcSOnP8VYtkr9Ya8Nvf7oYL98YDsM1CLMYIurYvfVUU4AGkzBsovwssT0bq.pdf",
      "type":"menu",
      "title":"Some menu title etc"
   }
]'::jsonb j)
select jsonb_array_elements(j) r from v) select r->>'file' from a where r->>'type' = 'menu';
                                    ?column?
---------------------------------------------------------------------------------
 zx5rP8EoacyfhqGndcSOnP8VYtkr9Ya8Nvf7oYL98YDsM1CLMYIurYvfVUU4AGkzBsovwssT0bq.pdf
(1 row)