To supplement my suggestions in a comment response to @a_horse_with_no_name's correct answer above:
In the end, in all, you need
- a combo of
COALESCE
- with a clob-compatible fallback of json array
- and
RETURNING CLOB
in each json_agg*
function (to be safe: it's only needed on the one wrapping content larger than varchar2(4000)
and any json_agg*
function wrapping it (ie: both inner object and outer array)
- on each thing that could return an empty resultset
Example:
SELECT
coalesce(
json_arrayagg(
json_object(
'something' value 'Something',
'staticEmptyArrayString' value to_clob('[]'),
'staticEmptyArrayReally' value to_clob('[]') format json,
'reallyEmptyArrayNull' value (SELECT to_clob('') FROM dual),
'reallyEmptyArray' value COALESCE((SELECT to_clob('') FROM dual), to_clob('[]')) format json,
'reallyEmptyArrayToo' value COALESCE((SELECT to_clob('') FROM dual), to_clob('[]')) format json,
'reallyEmptyArrayAlso' value COALESCE((SELECT to_clob('') FROM dual), to_clob('[]'))
format json
returning clob
)
returning clob
),
to_clob('[]')
) AS json_out
FROM dual;
begets:
[
{
"something": "Something",
"staticEmptyArrayString": "[]",
"staticEmptyArrayReally": [],
"reallyEmptyArrayNull": null,
"reallyEmptyArray": [],
"reallyEmptyArrayToo": [],
"reallyEmptyArrayAlso": []
}
]