简体   繁体   中英

PostgreSQL: Query elements in a JSON array

I have a database table like the following:

---------------------------------------
| id | json_array (jsonb)             |
---------------------------------------
|  1 | [{"a": 1}, {"a": 5}, {"a": 1}] |
|  2 | [{"a": 2}]                     |
|  3 | [{"a": 1}]                     |
---------------------------------------

I want to use PostgreSQL's JSON query abilities to select certain sub dictionaries in the json_array array, eg dictionaries where "a": 1 .

The output should be

------------------
| id | json_dict |
------------------
|  1 | {"a": 1}  |
|  1 | {"a": 1}  |
|  3 | {"a": 1}  |
------------------

The following query works for the first element in each array, but I want to check for all of them:

SELECT id, json_array -> 0
FROM my_table
WHERE json_array -> 0 -> "a" = 1;

Assuming this is a JSONB column, you can use the @> operator with a json object:

select *
from my_table
where json_array @> '[{"a": 1}]';

Online example: https://rextester.com/SACUDU51598

If you want all objects as rows, you need to unnest the array:

select t.id, e.obj
from data t
  cross join jsonb_array_elements(json_array) as e(obj)
where e.obj = '{"a": 1}'

Online example: https://rextester.com/DLG27322

demo:db<>fiddle

You can expand your array elements into one element each row with jsonb_array_elements() . This can be filtered:

SELECT
    id,
    elems.value
FROM
    mytable,
    jsonb_array_elements(data) elems
WHERE
    elems.value = '{"a":1}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM