按值true,NULL或'null'过滤JSON对象

时间:2020-04-18 12:26:14

标签: json postgresql filter

我想在表“ Test”中添加一个名为“ MyJsonObject”的新列。如果新列为true,则仅应包含值,而不是NULL或文本为'null'。

可以使用json_strip_nulls来过滤作为值的NULL,但是如何过滤其他值为false和'null'的文本呢?

json_strip_null仅适用于NULL值

myjsonstring                                                           |
-----------------------------------------------------------------------|
{"column_1":false,"column_2":false,"column_3":true,"column_4":"red"}   | 
{"column_1":false,"column_2":false,"column_3":true,"column_4":"yellow"}| 
{"column_1":false,"column_2":true,"column_3":true}                     | 
{"column_1":true,"column_2":false,"column_3":true,"column_4":"NULL"}   |

我想得到:

myjsonstring                                                           |
-----------------------------------------------------------------------|
{"column_3":true,"column_4":"red"}   |
{"column_3":true,"column_4":"yellow"}|
{"column_2":true,"column_3":true}    |
{"column_1":true,"column_3":true     |

1 个答案:

答案 0 :(得分:0)

您需要取消嵌套元素,然后将它们聚合回去:

select t.myjsonstring, x.new_json
from the_table t
  cross join lateral (
    select jsonb_object_agg(k,v) as new_json
    from jsonb_each(t.myjsonstring) as j(k,v)
    where v is not null
      and v::text not in ('false', 'NULL')
  ) as x