Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

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)
share|improve this answer
1  
This works for json, but not for jsonb. It should be SELECT 'name3' , json_array_elements( (column1->'name3')::json) FROM table1; –  Neil Nov 2 '14 at 14:46
    
It also does not get the row numbers of the array. –  Neil Nov 2 '14 at 14:52
up vote 1 down vote accepted

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?

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.