Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgres select item from json in json_agg

with a as(
SELECT '[{"residential" : 100}, {"childcare" : 200}, {"open space" : 50}]'::jsonb t
)
select t->'childcare' from a

this keeps returning null when it should give me back 200.

same thing if I do -->

https://www.postgresql.org/docs/current/functions-json.html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your data is an array of jsonb objects; you want to search the array for the object that has key childcare, and return the associated value.

For this, you would typically use a lateral join and jsonb_array_elements to unnest the array, then filter the resulting objects with operator ?.

So:

select x ->> 'childcare' childcare
from a
inner join lateral jsonb_array_elements(a.t) as x(elt) on x.elt ? 'childcare' 

Note that ->> should be used instead of -> in the select clause : the former gives you back a text value, while the latter returns jsonb.

Demo on DB Fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading