如何在 PL/pgSQL 代码块中将 integer[] 转换为 jsonb

How to convert integer[] to jsonb in a PL/pgSQL code block

如何将integer[]转换成jsonb

declare ids int[];
declare jsonids jsonb;

jsonids := array(select id from student); -- what should I do here?

你可以试试这个

select array_to_json(array_agg(id)) into jsonids from student

使用to_jsonb():

jsonids := to_jsonb(ARRAY(SELECT id FROM student));

或:

SELECT INTO jsonids to_jsonb(ARRAY(SELECT id FROM student));

array_to_json() 仅对在 json 中换行仍然有用(而不是 jsonb!)。 The manual:

Converts an SQL array to a JSON array. The behavior is the same as to_json except that line feeds will be added between top-level array elements if the optional boolean parameter is true.

参见:

  • Store query result in a variable using in PL/pgSQL

转换回来: