I'm using Postgres 9.2 to generate some JSON data. For each nested table I'm doing this nested set of functions:
SELECT array_to_json(
coalesce(
array_agg(
row_to_json(foo)),
ARRAY[]::json[])
)
FROM foo
The effect is to create a json array with each row being the json collection for the row. The coalesce ensures that I get an empty array rather than nil if the table is empty. In most cases foo is actually a subquery but I don't think that is relevent to the question.
I want to create a function table_to_json_array(expression) such that this has the same effect as above:
SELECT table_to_json_array(foo) FROM foo
I need to use this lots so I was planning to create a Postgres function to have the effect of the combination of these calls to clean up my queries. Looking at the documentation it seems as if I need to create an aggregate rather than a function to take a table argument but those look like I would need to reimplement array_agg myself.
Have I missed something (possibly just the type a function would need to take)? Any suggestions?