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

问题描述 投票:0回答:3

给定一个值为

的 jsonb 字段
{
  values: [null, 'test', { key: 'value' }]
}

是否可以返回

的输出
{
  values: [ 'test', { key: 'value' }]
}

我查看了文档并发现了一些功能,例如 jsonb_strip_nulls() 这仅适用于具有空值的键和 数组删除() 我无法使用 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)

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

{
  values: [null, null, null]
}

以上查询不返回

{
  values: []
}

在这种情况下。

如有任何帮助,我们将不胜感激!谢谢...

postgresql jsonb postgresql-9.5
3个回答
6
投票

对于 PostgreSQL 12:

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

4
投票

使用

coalesce
你可以这样实现:

WITH    test( data ) AS (
            VALUES
                ( $${"values": [null, "test", { "key": "value" }]}$$::jsonb ),
                ( $${"values": [null, null, null]}$$::jsonb )
        )
SELECT  jsonb_set(
            d.data,
            '{values}',
            coalesce(
                jsonb_agg(t.elem) FILTER ( WHERE NOT (t.elem = 'null') ),
                $$[]$$::jsonb
            ),
            FALSE
        )
FROM    test d,
        jsonb_array_elements( d.data-> 'values') WITH ORDINALITY AS t(elem)
GROUP BY d.data;


               jsonb_set
----------------------------------------
 {"values": ["test", {"key": "value"}]}
 {"values": []}
(2 rows)

注意:我使用

FILTER
而不是
WHERE
检查
null
,但使用
coalesce
时,您的查询也应该有效。


0
投票

对一个冷问题的迟到回答。这是该作业的可重用函数。

create or replace function jsonb_array_strip_nulls(arg_j jsonb)
returns jsonb language sql immutable as 
$$
 select coalesce(jsonb_agg(j order by o), '[]') 
   from jsonb_array_elements(arg_j) with ordinality as t(j, o)
  where j != 'null'
$$;
© www.soinside.com 2019 - 2024. All rights reserved.