将行嵌套到多个json对象中

时间:2019-11-13 18:44:08

标签: sql json database postgresql

目前,我有一个表my_table,其中包含列(id,product_id,text),并将数据转换为json对象,如下所示:

SELECT
  json_agg(
    json_build_object(
      'id', t.id,
      'parent_id', t.product_id,
      'text', t.text
    )
  )
FROM my_table AS t

现在我要向my_table添加更多列,我需要从该表的选定行列表中的每一行返回一个JSON对象。 基本上,talbe列将为(id,product_id,text1,text2,text3)

我想返回3个相同的对象,并带有1个不同的text值(用于text1,text2,text3)

我该如何实现?

1 个答案:

答案 0 :(得分:1)

使用unnest()将一行显示为三行:

select id, product_id, unnest(array[text1, text2, text3]) as text
from my_table

通过以上查询创建json数组:

select
    json_agg (
        json_build_object(
            'id', id,
            'product_id', product_id,
            'text', text
        )
    )
from (
    select id, product_id, unnest(array[text1, text2, text3]) as text
    from my_table
    ) t

select
    json_agg (
        json_build_object(
            'id', id,
            'product_id', product_id,
            'text', text
        )
    )
from my_table
cross join unnest(array[text1, text2, text3]) as text