【问题标题】:Filter JSON object by the values true, NULL or 'null'按值 true、NULL 或 'null' 过滤 JSON 对象
【发布时间】:2020-07-31 23:36:03
【问题描述】:

我想在“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     |

【问题讨论】:

    标签: json postgresql filter


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多