Re: [HACKERS] json_agg produces nonstandard json - Mailing list pgsql-hackers

From Tom Lane
Subject Re: [HACKERS] json_agg produces nonstandard json
Date
Msg-id 22923.1493921817@sss.pgh.pa.us
Whole thread Raw
In response to [HACKERS] json_agg produces nonstandard json  (Jordan Deitch <jwdeitch@gmail.com>)
Responses Re: [HACKERS] json_agg produces nonstandard json  (Jordan Deitch <jwdeitch@gmail.com>)
List pgsql-hackers
Jordan Deitch <jwdeitch@gmail.com> writes:
> A json(b)_agg() will produce the following result when no results are
> passed in:
> "[null]"
> per:
> select jsonb_agg((select 1 where false));

Looks fine to me.

> I believe, generally speaking, '[]' would be the more appropriate output.

Why?  What you gave it was one null value.  An empty array result would
imply that there were zero inputs, which is wrong.

Perhaps you're confused about the way scalar sub-selects work?  The
above is equivalent to "select jsonb_agg(null::integer)"; it's not
the same as

# select jsonb_agg(1) where false;jsonb_agg 
-----------
(1 row)

Now you could legitimately argue that this case, where there are zero
input rows, should produce '[]' rather than a SQL null.  But I think we
had that discussion already, and agreed that this behavior is more in
keeping with the behavior of SQL's standard aggregates, notably SUM().
You can use coalesce() to inject '[]' (or whatever result you want) for
the no-rows case:

# select coalesce(jsonb_agg(1), '[]') where false;coalesce 
----------[]
(1 row)
        regards, tom lane



pgsql-hackers by date:

Previous
From: Joe Conway
Date:
Subject: Re: [HACKERS] CTE inlining
Next
From: Tom Lane
Date:
Subject: Re: [HACKERS] Reducing runtime of stats regression test