Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL 9.4 expand jsonb int array into table with row numbers

Trying to wrap my head around postgresql 9.4 jsonb and would like some help figuring out how to do the following.

Given the following example jsonb:

‘{“name1” : value1, “name2” : value2, “name3” : [int1, int2, int3] }’::jsonb AS table1.column1

Wanted: Return the “name3” array only, as a table with a return signature of

TABLE( var_name varchar, var_value int, var_row_num int)

So the resulting data would look like this:

(‘name3’, int1, 1)
(‘name3’, int2, 2)
(‘name3’, int3, 3)

Assume the array could be any length except zero and 'name3' is guaranteed to exist.

like image 248
Neil Avatar asked Feb 26 '26 11:02

Neil


2 Answers

You can use json_array_elements to unnest the json array that results from column1->'name3'

SELECT 'name3' ,json_array_elements(column1->'name3')
FROM table1;

results

(‘name3’, int1)
(‘name3’, int2)
(‘name3’, int3)
like image 116
Bruno Calza Avatar answered Mar 02 '26 13:03

Bruno Calza


This seems to solve the problem (thanks, Bruno), but it seems like more code than should be necessary?

WITH x AS (SELECT 'name3' as aname, jsonb_array_elements(column1->'name3') AS some_value FROM table1)
SELECT x.*, row_number() OVER () FROM x;

Anyone have a better solution?

like image 24
Neil Avatar answered Mar 02 '26 13:03

Neil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!