Last Updated: February 25, 2016
· stuartc

Exporting Postgres queries as JSON

SELECT json_agg(table_name) FROM table_name

For an added bonus, export to file:

\copy (SELECT json_agg(table_name) FROM table_name) To '/tmp/out.json'

More information about Aggregate Functions like json_agg().

And more information about working with JSON with Postgres.

This should work out the box with 9.3, and some of the functions have been backported to 9.2.