从PostgreSQL中的jsonb数组获取元素作为扁平字符串

时间:2018-09-26 15:51:10

标签: sql arrays postgresql jsonb

我有一个x列,其数据类型为jsonb

,值看起来像:

    public static String readfromredis(String key,List <String> values) {
        String k = null;


          for (int i=0;i<values.size();i++) {
             k= jedis.get(key);
              System.out.println(k);
            }
          return k;
}

如何使用Postgres查询返回包含所有元素的字符串数组?

类似这样的东西:

[“ 6cd”,“ text1”,“ label_text_1”,“描述”,“ 815”,“ text2”,“ label_text_2”,“ desc2”]

2 个答案:

答案 0 :(得分:2)

使用jsonb_array_elements(json_column)获取数组元素,使用jsonb_each_text(elem)获取这些元素中所有嵌套对象的值:

with my_table(id, json_column) as (
values(
    1, 
    '[
        {"key": "6cd", "type": "text1", "label": "label_text_1", "content": "description"},
        {"key": "815", "type": "text2", "label": "label_text_2", "content": "desc2"}
    ]'::jsonb)
)

select id, array_agg(val)
from my_table
cross join jsonb_array_elements(json_column) as a(elem)
cross join jsonb_each_text(elem) as e(key, val)
group by id

 id |                             array_agg                             
----+-------------------------------------------------------------------
  1 | {6cd,text1,label_text_1,description,815,text2,label_text_2,desc2}
(1 row) 

答案 1 :(得分:2)

select array_agg(value) from t
join lateral jsonb_array_elements(col) e(v)
on true 
join lateral jsonb_each_text(v)
on true