1
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}]}]}

I am trying to write a select query on this data which empties the destinations array incase any of the "Id" is null

So the output should be (empty destinations array in second row) :-

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}]}]}

How can I achieve this?

1
  • Does this answer answer your question? Commented Aug 17, 2021 at 0:05

1 Answer 1

1

You can use json_array_elements with a subquery to determine if a "destinations" key contains any null Id values in its array:

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

Output:

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}]}]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.