0

I have a table as shown below. the datatype of data is json (json does not have keys but just array of values)

guid                                 | type  | data           |       
9cf100e8-87a8-4ce7-b187-b618bf2dc156 | email | ["[email protected]"] 
03d5b41c-b834-4399-95dc-c51b1e214fb3 | email | ["[email protected]"] 

I want to write a query to select all rows if the column data contains "[email protected]"

2
  • 2
    Possible duplicate of How do I query using fields inside the new PostgreSQL JSON datatype? Commented Nov 16, 2015 at 11:37
  • The response given are all to navigate the json when the array is in key value format. When the json does not have keys but just array of values, how to frame the query?. I dont see an example of this case in official doc also Commented Nov 16, 2015 at 12:11

3 Answers 3

2

Use json_array_elements() to unpack a json array:

select guid, type, json_array_elements(data) elem
from guids;

                 guid                 | type  |     elem      
--------------------------------------+-------+---------------
 9cf100e8-87a8-4ce7-b187-b618bf2dc156 | email | "[email protected]"
 03d5b41c-b834-4399-95dc-c51b1e214fb3 | email | "[email protected]"
(2 rows)

Use a derived table to filter the data:

select *
from (
    select guid, type, json_array_elements(data)::text elem
    from guids
    ) sub
where elem = '"[email protected]"';

                 guid                 | type  |     elem      
--------------------------------------+-------+---------------
 9cf100e8-87a8-4ce7-b187-b618bf2dc156 | email | "[email protected]"
 03d5b41c-b834-4399-95dc-c51b1e214fb3 | email | "[email protected]"
(2 rows)
0
1

How about

select * from tbl where data::text like '%[email protected]%'
0
0

instead of unpacking by json_array_elements(), you can unpack by json_array_elements_text()

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.