Skip to content
Advertisement

Query for array elements inside JSON type

I’m trying to test out the json type in PostgreSQL 9.3.
I have a json column called data in a table called reports. The JSON looks something like this:

I would like to query the table for all reports that match the ‘src’ value in the ‘objects’ array. For example, is it possible to query the DB for all reports that match 'src' = 'foo.png'? I successfully wrote a query that can match the "background":

But since "objects" has an array of values, I can’t seem to write something that works. Is it possible to query the DB for all reports that match 'src' = 'foo.png'? I’ve looked through these sources but still can’t get it:

I’ve also tried things like this but to no avail:

I’m not an SQL expert, so I don’t know what I am doing wrong.

Advertisement

Answer

json in Postgres 9.3+

Unnest the JSON array with the function json_array_elements() in a lateral join in the FROM clause and test for its elements:

The CTE (WITH query) just substitutes for a table reports.
Or, equivalent for just a single level of nesting:

->>, -> and #> operators are explained in the manual.

Both queries use an implicit JOIN LATERAL.

SQL Fiddle.

Closely related answer:

jsonb in Postgres 9.4+

Use the equivalent jsonb_array_elements().

Better yet, use the new “contains” operator @> (best in combination with a matching GIN index on the expression data->'objects'):

Since the key objects holds a JSON array, we need to match the structure in the search term and wrap the array element into square brackets, too. Drop the array brackets when searching a plain record.

Detailed explanation and more options:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement