如何使用数据将数组更改为jsonb?

时间:2019-03-20 23:56:02

标签: sql json postgresql

我有一个数组列,其数据如下:

{foo,bar}
{foo}
{foo,foobar}
...

我想将其转换为jsonb:

[{"my_key": "foo", "state": true}, {"my_key": "bar", "state": true}]
[{"my_key": "foo", "state": true}]
[{"my_key": "foo", "state": true}, {"my_key": "foobar", "state": false}]
...

“状态”为

case when type = ANY('{"foo","bar"}'::text[]) then true
else false

我该怎么做? 谢谢

2 个答案:

答案 0 :(得分:2)

您可以取消嵌套值,并通过横向联接将它们聚合回去:

with t (data) as (
values 
  (array['foo','bar']),
  (array['foo']),
  (array['foo', 'foobar'])
)
select x.*
from t
  cross join lateral (
      select jsonb_agg(jsonb_build_object(
                          'my_key', x.type, 
                          'state', x.type = any(array['foo','bar']))
                       ) as val
      from unnest(t.data) as x(type)
  ) x;

返回:

val                                                                     
------------------------------------------------------------------------
[{"state": true, "my_key": "foo"}, {"state": true, "my_key": "bar"}]    
[{"state": true, "my_key": "foo"}]                                      
[{"state": true, "my_key": "foo"}, {"state": false, "my_key": "foobar"}]

在线示例:https://rextester.com/MWUER75686

答案 1 :(得分:0)

尝试一下:

begin;

create table t (keys text[]);

insert into t values ('{"foo","bar"}'), ('{"foo"}'), ('{"foo","foobar"}');

create or replace function array2jsonb(a text[]) returns jsonb AS $$
    DECLARE
        k text;                 -- the current key
        j jsonb := '[]'::jsonb; -- the jsonb array we collect the objects in
    BEGIN
        -- We loop over each key in the given array.
        FOREACH k IN ARRAY a
        LOOP
            -- Concat a JSON object to the JSON array for every key in the array.
            j = j || ('{"my_key":"' || k || '","state":' ||
                case when k = ANY('{"foo","bar"}'::text[])
                     then true
                     else false
                     end || '}')::jsonb;
        END LOOP;
        return j;
    END
$$ LANGUAGE plpgsql;

select array2jsonb(keys) from t;

rollback;

结果:

+--------------------------------------------------------------------------+
| array2jsonb                                                              |
|--------------------------------------------------------------------------|
| [{"state": true, "my_key": "foo"}, {"state": true, "my_key": "bar"}]     |
| [{"state": true, "my_key": "foo"}]                                       |
| [{"state": true, "my_key": "foo"}, {"state": false, "my_key": "foobar"}] |
+--------------------------------------------------------------------------+

参考文献: