在 Postgres JSONB 字段中仅选择非 NULL 键

Selecting only non-NULL keys in a Postgres JSONB field

我有一个带有 JSONB 列的 postgres 9.6 table

> SELECT id, data FROM my_table ORDER BY id LIMIT 4;

 id |               data    
----+---------------------------------------
  1 | {"a": [1, 7], "b": null, "c": [8]}
  2 | {"a": [2, 9], "b": [1], "c": null}
  3 | {"a": [8, 9], "b": null, "c": [3, 4]}
  4 | {}

如您所见,一些 JSON 键具有 null 值。

我想排除这些 - 有没有一种简单的方法可以 SELECT 仅生成非 null 键值对:

 id |               data    
----+---------------------------------------
  1 | {"a": [1, 7], "c": [8]}
  2 | {"a": [2, 9], "b": [1]}
  3 | {"a": [8, 9], "c": [3, 4]}
  4 | {}

谢谢!

您可以使用jsonb_strip_nulls()

select id, jsonb_strip_nulls(data) as data
from my_table;

在线示例:http://rextester.com/GGJRW83576

请注意,此函数不会删除数组中的 null 个值。