从对象数组中提取键值对

时间:2020-05-06 13:48:51

标签: sql json postgresql

我有一个名为“ apples”的表,如下所示:

| not_a_pk | data (jsonb)                                                                                                                 |
|----------|-----------------------------------------------------------------------------------------------------------------------|
| 1        | [{"key":"color", "value":"red", "notes":"good apple"}, {"key":"size", "value":"large", "notes":"pretty large apple"}] |
| 2        | [{"key":"color", "value":"green", "notes":"too green"}, {"key":"size", "value":"small", "notes":"could be bigger"}]   |
| 2        | [{"key":"color", "value":"purple", "notes":"weird"}, {"key":"size", "value":"miniscule", "notes":"actually a grape"}] |

我想用键“ key”和“ value”提取对象的一部分,并按not_a_pk分组,这样看起来像这样:

| not_a_pk | data                                                                                                                                        |
|----------|---------------------------------------------------------------------------------------------------------------------------------------------|
| 1        | [{"key":"color", "value":"red"}, {"key":"size", "value":"large"}]                                                                           |
| 2        | [{"key":"color", "value":"green"}, {"key":"size", "value":"small"}, {"key":"color", "value":"purple"}, {"key":"size", "value":"miniscule"}] |

我已经能够在一个键下获取所有值,例如{“ key”:[“ color”,“ size”,“ color”,“ size”]},但我不知道如何使用单独的键将它们保留为常规对象。

1 个答案:

答案 0 :(得分:3)

您需要取消嵌套数组元素,构造新的JSON对象,然后聚合回数组:

select a.not_a_pk, 
       jsonb_agg(jsonb_build_object('key', x.item -> 'key', 'value', x.item -> 'value')) as data
from apples a
  cross join jsonb_array_elements(a.data) as x(item)
group by a.not_a_pk
order by a.not_a_pk;

Online example