代码之家  ›  专栏  ›  技术社区  ›  Zmur

jsonb_agg函数创建额外的json字段

  •  0
  • Zmur  · 技术社区  · 8 月前

    为什么Postgres jsonb_agg函数将输出封装到附加的JSON字段中?

    SELECT jsonb_agg(t) AS json_array
    FROM (SELECT jsonb_set('[{"f1": "1","f2": null},  2,  null,  3]', '{0,f1}', '"DELETEME"',true)) t
    

    它返回的是:

    [{"jsonb_set": [{"f1": "DELETEME", "f2": null}, {"f3": "1", "f4": null}]}]
    

    如何避免这种行为?当我需要它返回时:

    [{"f1": "DELETEME", "f2": null}, {"f3": "1", "f4": null}]
    
    1 回复  |  直到 8 月前
        1
  •  2
  •   Dogbert    8 月前

    您正在转换整个表的别名 t 到json,而不仅仅是那一列。改变 t t.jsonb_set 。这样可以:

    =# SELECT jsonb_agg(t.jsonb_set) AS json_array
       FROM (SELECT jsonb_set('[{"f1": "1","f2": null},  2,  null,  3]', '{0,f1}', '"DELETEME"',true)) t;
                       json_array
    ------------------------------------------------
     [[{"f1": "DELETEME", "f2": null}, 2, null, 3]]
    (1 row)