Use jsonb_array_elements(), e.g.:
with data(js) as (
select
'[
{ "type": "foo", "desc": "example" },
{ "type": "foo", "desc": "second example" },
{ "type": "bar", "desc": "third example" }
]'::jsonb
)
select elem->>'type' as "type", count(elem->'type')
from data, jsonb_array_elements(js) elem
group by 1;
type | count
------+-------
foo | 2
bar | 1
(2 rows)
The function should look like this:
create or replace function check_duplicates(source jsonb, key text)
returns boolean language sql as $$
select max(count) > 1
from (
select count(elem->key)
from jsonb_array_elements(source) elem
group by elem->key
) s
$$;
Usage:
with data(js) as (
select
'[
{ "type": "foo", "desc": "example" },
{ "type": "foo", "desc": "second example" },
{ "type": "bar", "desc": "third example" }
]'::jsonb
)
select check_duplicates(js, 'type')
from data;
check_duplicates
------------------
t
(1 row)