0

how can I change a list of jsonb structure (key/value) to object, dynamically??

for example:

from

[{'key':'size','value':'200'},{'key':'pound','value':'200'},{'key':'square','value':'true'},...]

to

{'size':'200','pound':'200','square':'true',....}

select jsonb_array_elements( topi.other_information)->'key' as key_field,
jsonb_array_elements( topi.other_information)->'value' as value_field
from items_data.tbl_items topi

but when I use jsonb_build_object i need to know the keys. Is there a way to do it?

1 Answer 1

3

You need to unnest the array then aggregate it back using jsonb_object_agg()

select t.id, jsonb_object_agg(x ->> 'key', x -> 'value')
from items_data.tbl_items t
  cross join jsonb_array_elements(t.other_information) as x(element)
group by t.id

t.id is the assumed primary key of the table which is needed to keep the values for the same row together during unnesting and grouping.


If you need that frequently, maybe it makes sense to write a function:

create function flatten(p_input jsonb)
  returns jsonb
as
$$
  select jsonb_object_agg(x ->> 'key', x -> 'value')
  from jsonb_array_elements(p_input) as x(element);
$$
language sql
immutable;

Then you can use it without a group by:

select t.id, flatten(t.other_information)
from items_data.tbl_items t
Sign up to request clarification or add additional context in comments.

3 Comments

Because I just finished the same solution: here's my fiddle dbfiddle.uk/…
.... i was trying to do the same thing with "with"... ``` with temp_table_items as ( select id,jsonb_array_elements( topi.other_information)->>'key' as key_field, jsonb_array_elements( topi.other_information)->>'value' as value_field,item_number,group_number,quantity,unit_value,total_value,brand, model_version,manufacturer,item_final_details from items_data.tbl_items topi ) select id,jsonb_build_object('is_foreign', case when key_field='is_foreign' and value_field = 'true' then true else false end...``` thank you so much!!!! it works nice your query is much better. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.