I'm returning a JSON array from a PostgreSQL request with the json_agg
function. However, when no row is found, json_agg
returns an empty string instead of an empty JSON array []
(square brackets are mandatory if I understand json.org).
For example:
SELECT json_agg(t.*) FROM (SELECT 'test' AS mycol WHERE 1 = 2) AS t ;
returns an empty string, whereas the same command with '1 = 1' returns a valid JSON array (tested with PostgreSQL 9.5).
Any idea?
Postgres offers us the json_agg() function, which takes an input values and aggregates them as a JSON array.
Aggregate Rows into a JSON Array Using the json_agg() Function. Postgres offers us the json_agg() function, which takes input values and aggregates them as a JSON array.
PostgreSQL provides two native operators -> and ->> to help you query JSON data. The operator -> returns JSON object field as JSON. The operator ->> returns JSON object field as text.
In Postgres, if you select a key that does not exist it will return null. so u can check the existence of a key by checking the null value of that key.
json_agg
returns null from an empty set:
select json_agg(t.*) is null
from (select 'test' as mycol where 1 = 2) t ;
?column?
----------
t
If you want an empty json array coalesce
it:
select coalesce(json_agg(t.*), '[]'::json)
from (select 'test' as mycol where 1 = 2) t ;
coalesce
----------
[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With