【问题标题】:How to remove an object from json on condition Postgresql如何在条件 Postgresql 的情况下从 json 中删除对象
【发布时间】:2021-08-16 18:58:10
【问题描述】:
JsonData
{"DestinationLists" : [{"name" : "Slingshot", "destinations" : [{"Id" : 4155}, {"Id" : 191}, {"Id" : 165}, {"Id" : 183}]}]}
{"DestinationLists" : [{"name" : "TVNZ, Mediaworks, Choice", "destinations" : [{"Id" : null}]}, {"name" : "TVNZ, Discovery", "destinations" : [{"Id" : 165}, {"Id" : 183}, {"Id" : 4155}]}]}
{"DestinationLists" : [{"name" : "SecondTest", "destinations" : [{"Id" : 103}, {"Id" : 105}]}, {"name" : "ThirdTest", "destinations" : [{"Id" : 3}, {"Id" : 5}]}]}

我正在尝试对此数据编写一个选择查询,以清空destinations 数组,以防"Id" 中的任何一个为null

所以输出应该是(第二行空destinations数组):-

JsonData
{"DestinationLists" : [{"name" : "Slingshot", "destinations" : [{"Id" : 4155}, {"Id" : 191}, {"Id" : 165}, {"Id" : 183}]}]}
{"DestinationLists" : [{"name" : "TVNZ, Mediaworks, Choice", "destinations" : []}, {"name" : "TVNZ, Discovery", "destinations" : [{"Id" : 165}, {"Id" : 183}, {"Id" : 4155}]}]}
{"DestinationLists" : [{"name" : "SecondTest", "destinations" : [{"Id" : 103}, {"Id" : 105}]}, {"name" : "ThirdTest", "destinations" : [{"Id" : 3}, {"Id" : 5}]}]}

我怎样才能做到这一点?

【问题讨论】:

  • answer 回答你的问题了吗?

标签: sql json postgresql


【解决方案1】:

您可以将json_array_elements 与子查询一起使用来确定"destinations" 键是否在其数组中包含任何空的Id 值:

select json_build_object('DestinationLists', 
    (select array_to_json(
         array_agg(
            case when not exists (select 1 from json_array_elements(v.value -> 'destinations') v1 
                 where (v1.value -> 'Id')::text = 'null')
            then v.value::jsonb
            else jsonb_set(v.value::jsonb, '{destinations}'::text[], '[]'::jsonb) end
        )
     ) 
     from json_array_elements(d1.js -> 'DestinationLists') v)
)
from data d1

输出:

JsonData
{"DestinationLists" : [{"name" : "Slingshot", "destinations" : [{"Id" : 4155}, {"Id" : 191}, {"Id" : 165}, {"Id" : 183}]}]}
{"DestinationLists" : [{"name" : "TVNZ, Mediaworks, Choice", "destinations" : []}, {"name" : "TVNZ, Discovery", "destinations" : [{"Id" : 165}, {"Id" : 183}, {"Id" : 4155}]}]}
{"DestinationLists" : [{"name" : "SecondTest", "destinations" : [{"Id" : 103}, {"Id" : 105}]}, {"name" : "ThirdTest", "destinations" : [{"Id" : 3}, {"Id" : 5}]}]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多