array_to_json 的 PostgreSQL 奇怪行为

PostgreSQL strange behaviour with array_to_json

我想在转换为 JSON 之前使用 array_agg 消除空值,但空值再次出现在 JSON 输出中。 这是一个演示行为的最小示例:

select id, array_agg(alias), array_to_json(array_agg(alias))
from (values (1, 'foo'), (1, 'bar'), (2, null)) t(id, alias)
group by id;

结果集是这样的:

id|array_agg|array_to_json|
--+---------+-------------+
 1|{foo,bar}|["foo","bar"]|
 2|{}       |[null]       |

array_agg 的文档指出它“将所有输入值(包括空值)收集到一个数组中。”显示为空的数组只是输出的格式化方式,但实际上它仍然包含 nullhttps://www.postgresql.org/docs/current/functions-aggregate.html

要为 null 值获取一个空数组,请使用带有 filter 子句的 json_aggcoalesce:

select 
  id,
  coalesce(json_agg(alias) filter (where alias is not null), '[]'::json)
from (values (1, 'foo'), (1, 'bar'), (2, null)) t(id, alias)
group by id;