Postgres 合并为空的 JSONB 数组

Sam*_*Rad 8 sql arrays postgresql coalesce jsonb

如何将coalescenull列转换为空JSONB数组?这不起作用:

SELECT jsonb_array_elements(coalesce(null_column, '{}'::jsonb))
FROM table
WHERE id = 13;

-- ERROR:  cannot extract elements from an object
Run Code Online (Sandbox Code Playgroud)

既不是这个:

SELECT jsonb_array_elements(coalesce(null_column, '[]'::jsonb))
FROM table
WHERE id = 13;

-- ERROR:  cannot extract elements from a scalar
Run Code Online (Sandbox Code Playgroud)

Fuz*_*ree 6

{}是一个对象但jsonb_array_elements需要一个数组,所以替换{}[]

确保两个参数都返回一个 jsonb 数组。例如,如果您的列是整数,则可以使用concat添加方括号并::jsonb进行转换

SELECT jsonb_array_elements(coalesce(concat('[',my_column,']')::jsonb,'[]'::jsonb))
Run Code Online (Sandbox Code Playgroud)

  • @norbertpy 你确定 col 应该为 null,而不是 json 中表示 null 的字符串吗? (3认同)