Join two Json arrays to one with key and value

All we need is an easy explanation of the problem, so here it is.

I have two jsonb columns(keys,values).
Eg: keys colum value = ["key1","key2","key3","key4"]
values column = ["val1","val2","val3","val4"]

I want to write a select query to get the output as below based on the array index.

{"key1":"val1","key2":"val2","key3":"val3","key4":"val4"}

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You need to unnest the arrays then aggregate everything back into a single JSON value:

select x.value
from the_table t
  cross join lateral (
    select jsonb_object_agg(k.ky, v.value) as value
    from jsonb_array_elements_text(t.keys) with ordinality as k(ky,idx)
       join jsonb_array_elements(t.values) with ordinality as v(value,idx) on k.idx = v.idx
  ) x

Online example

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply