PostgreSQL JSON Arrays – Joining Key and Value Pairs

arrayjsonpostgresql

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"}

Best Answer

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