Cast json array to postgres array and preserve order of elements

Started by otar shavadzeover 5 years ago3 messages
#1otar shavadze
oshavadze@gmail.com

When I want t to convert json array into postgres array, I do:

with t(j) as(

select '{"my_arr":[3,1,2]}'::json
)
SELECT ARRAY(SELECT json_array_elements_text(j->'my_arr')) from t

It works like a charm and I never noticed any problem, but I'm asking here
just to make sure, order of elements will be preserved always?
Is that guaranteed in above example, or not?

Thanks.

#2Andrew Dunstan
andrew.dunstan@2ndquadrant.com
In reply to: otar shavadze (#1)
Re: Cast json array to postgres array and preserve order of elements

On 5/10/20 8:21 AM, otar shavadze wrote:

When I want t to convert json array into postgres array, I do:

with t(j) as(
    select '{"my_arr":[3,1,2]}'::json
)
SELECT ARRAY(SELECT json_array_elements_text(j->'my_arr')) from t

It works like a charm and I never noticed any problem, but I'm asking
here just to make sure,  order of elements will be preserved always? 
Is that guaranteed in above example, or not?

yes. The order is significant and the elements are produced in array order.

cheers

andrew

--
Andrew Dunstan https://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

#3otar shavadze
oshavadze@gmail.com
In reply to: Andrew Dunstan (#2)
Re: Cast json array to postgres array and preserve order of elements

Great, thanks very much Andrew!

On Sun, May 10, 2020 at 7:08 PM Andrew Dunstan <
andrew.dunstan@2ndquadrant.com> wrote:

Show quoted text

On 5/10/20 8:21 AM, otar shavadze wrote:

When I want t to convert json array into postgres array, I do:

with t(j) as(
select '{"my_arr":[3,1,2]}'::json
)
SELECT ARRAY(SELECT json_array_elements_text(j->'my_arr')) from t

It works like a charm and I never noticed any problem, but I'm asking
here just to make sure, order of elements will be preserved always?
Is that guaranteed in above example, or not?

yes. The order is significant and the elements are produced in array order.

cheers

andrew

--
Andrew Dunstan https://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services