0

Is it possible to use LIKE operator for single key/value inside array of objects for jsonb field in PostgreSQL 9.4? For example I have:

 id |                  body                                                              
------------------------------------------------------------
  1 | {"products": [{"name": "qwe", "description": "asd"}, {"name": "zxc", "description": "vbn"}]}

I know, I can get a product with something like this:

select * from table where 'body'->'products' @> '[{"name": "qwe"}]'::jsonb

The question is: can I get this product if I don't know full name of it?

1 Answer 1

1

Try to get the key and value by using jsonb_each() function:

WITH json_test(data) AS ( VALUES
  ('{"products": [{"name": "qwe", "description": "asd"}, {"name": "zxc", "description": "vbn"}]}'::JSONB)
)
SELECT doc.key,doc.value
FROM json_test jt,
  jsonb_array_elements(jt.data->'products') array_elements,
  jsonb_each(array_elements) doc
WHERE
  doc.key = 'name'
AND
  doc.value::TEXT LIKE '%w%';

Output will be the following:

 key  | value 
------+-------
 name | "qwe"
(1 row)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.