如何在 Postgresql 中获取数组的 JavaScript/JSON 数组?

How to get JavaScript/JSON array of array in Postgresql?

JSON 对象格式冗长:

"[{"id":1,"name":"John"}, {"id":2,"name":"Jack"}]"

有时,重复的字段名称占用的 space 比实际数据多。为了节省带宽并加快页面加载速度,我想生成一个 JavaScript 字符串格式的数组并将其发送给客户端。例如对于此数据:

create table temp (
  id int,
  name text
);

insert into temp values (1, 'John'), (2, 'Jack');

我想要'[[1, "John"], [2, "Jack"]]'。我怎样才能做到这一点?

我不想通过键入来聚合列,因为那样很难维护。我也知道 postgresql 不允许像 JavaScript 这样的数组中有多个类型,所以一种可能是使用复合类型,但是 stringified/aggregated 结果最终在其中包含 '()'。

select array_to_json(array_agg(json_build_array(id, name)))
from temp;
       array_to_json       
---------------------------
 [[1, "John"],[2, "Jack"]]