My json looks like this:-
{"DestinationLists": [{"name": "TVNZ, Mediaworks, Choice", "destinations": []}, { "name": "TVNZ, Discovery", "destinations": [165, 183, 4155]}]}
My desired output is one row for each object in the array like:-
{"name" : "TVNZ, Mediaworks, Choice", "destinations" : []}
{"name" : "TVNZ, Discovery", "destinations" : [{"Id" : 165}, {"Id" : 183}, {"Id" : 4155}]}
My query is this:-
WITH ExpandedData AS (
SELECT
"Id",
setting,
json_build_object(
'name',
dl->>'name',
'destinations',
json_agg(
json_build_object('Id',dld::text::int)
)
) as DestinationListItem
FROM
feature.settings,
jsonb_array_elements(value->'DestinationLists') dl,
jsonb_array_elements(dl->'destinations') dld
GROUP BY
"Id",dl->>'name'
)
select * from ExpandedData
But this query is missing destinations where the array is empty so the result I am getting from the query is:-
{"name" : "TVNZ, Discovery", "destinations" : [{"Id" : 165}, {"Id" : 183}, {"Id" : 4155}]}
just one row instead of two. How do I update this query to get the desired outcome?
DBFiddle here:- https://www.db-fiddle.com/f/tDA7SajDoWhXrQaAa1j2qN/0
EDIT: I have been able to further drill down my problem, so the issue is basically happening from this line of the query:-
jsonb_array_elements(dl->'destinations') dld
Basically when the destinations array is empty then jsonb_array_elements does not return anything so I guess the right solution here would be to somehow return an empty array from jsonb_array_elements when an empty array is passed to it.