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

Project an array in jsonb

Suppose we have this table:

CREATE TEMPORARY TABLE TEST (FIELD jsonb);
INSERT INTO TEST VALUES ('[{"key": 1},{"key": 2}]');
SELECT field FROM TEST;

Result:

field
[{"key": 1}, {"key": 2}]

I would like to query the table in order to obtain this result:

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

field
[1, 2]

that is, to project every element in the array respect to their key.

Can’t find a simple way to do that.

>Solution :

You can use a JSON path query:

SELECT jsonb_path_query_array(field, '$[*].key') 
FROM test;

[*] iterates over all values in the array and .key then returns the value for each key.

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