json key:...,value:.... 到 postgresql 中的 value_key:value_value

json key:...,value:.... to value_key:value_value in postgresql

如何动态地将 jsonb 结构列表 (key/value) 更改为对象?

例如:

来自

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

{'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

但是当我使用 jsonb_build_object 时,我需要知道密钥。有办法吗?

您需要取消嵌套数组,然后使用 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 是 table 的假定主键,在取消嵌套和分组期间需要将同一行的值保持在一起。


如果你经常需要,也许写一个函数是有意义的:

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;

那你就可以不用group by:

select t.id, flatten(t.other_information)
from items_data.tbl_items t