简体   繁体   中英

SQL - Query for array elements inside hash in json

I have a table with a jsonb column of the below given structure.

my_json: {"records": [{"id":1, "name":"first"}, {"id":2, "name":"second"}, {"id":3, "name":"third"}]}

What i need is select all the ids present inside the records key. And I couldn't find any help anywhere for this json structure.

I have tried for the following queries, but couldn't actually get to a point that i want to reach.

"select my_json->>'records' from my_table where my_json->>'records' is not null AND my_json #> '{records}' != '[]'"

this actually gives the complete array, but what i need is the value of all the 'id' key in that.

could somebody help in sorting it out please.

Note: I use Postgres 9.5

you look for json_array_elements :

t=# with c(my_json) as (values (' {"records": [{"id":1, "name":"first"}, {"id":2, "name":"second"}, {"id":3, "name":"third"}]}'::json))
select json_array_elements(my_json->'records')->>'id' from c;
 ?column?
----------
 1
 2
 3
(3 rows)

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