如何从 postgres jsonb 数组中删除空值?

Dal*_*h88 3 postgresql jsonb postgresql-9.5

给定一个值为 jsonb 的字段

{
  values: [null, 'test', { key: 'value' }]
}
Run Code Online (Sandbox Code Playgroud)

是否有可能返回一个输出

{
  values: [ 'test', { key: 'value' }]
}
Run Code Online (Sandbox Code Playgroud)

我查看了文档,发现了一些函数,例如 jsonb_strip_nulls() ,它仅适用于具有空值的键和 array_remove() ,我无法使用 jsonb 。

我会用

UPDATE table 
  SET data = jsonb_set(data, '{values}'::text[], jsonb_agg(elem), false)
FROM data, 
     jsonb_array_elements(data-> 'values') WITH ORDINALITY AS t(elem, nr)
WHERE jsonb_typeof(elem) <> 'null'
GROUP BY (data.id)
Run Code Online (Sandbox Code Playgroud)

这对于大多数情况都可以正常工作,但我需要它来处理这种情况:

{
  values: [null, null, null]
}
Run Code Online (Sandbox Code Playgroud)

上述查询不返回

{
  values: []
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下。

任何帮助都是appriced!谢谢...

Ale*_*lov 6

对于 PostgreSQL 12:

select jsonb_path_query_array('{"values": [null, "test", { "key": "value" }]}', '$.values[*] ? (@ != null)')    
Run Code Online (Sandbox Code Playgroud)