Reputation: 243
I have array column with data like this:
{foo,bar}
{foo}
{foo,foobar}
...
and I want convert it to 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}]
...
where "state" is
case when type = ANY('{"foo","bar"}'::text[]) then true
else false
How can I do that? Thanks
Upvotes: 2
Views: 83
Reputation:
You can unnest the values and aggregate them back with a lateral join:
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;
returns:
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"}]
Online example: https://rextester.com/MWUER75686
Upvotes: 2
Reputation:
Try this:
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;
Result:
+--------------------------------------------------------------------------+
| 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"}] |
+--------------------------------------------------------------------------+
References:
Upvotes: 0