How to check if json array already contains a certain key?

Viewed 290

Let's say I have this json in my jsonb column

{
  "fields": [
    {
      "name": "firstName",
    },
    {
      "name": "lastName",
    },
    ...
}

How can I know if the "firstName" already exist?

I've tried this so far

SELECT field->>'fields' 
from person where (field->'name')::jsonb ? 'firstName';
2 Answers

Use the containment operator @>:

select field->>'fields'
from person
where field->'fields' @> '[{"name": "firstName"}]'

you can use json_array_elements to generate fields elements so you can filter based on 'name'.

SELECT field->>'fields', obj.*
from person, jsonb_array_elements_text(field->'fields') obj
where obj = '{"name": "firstName"}'

see dbfiddle

Related