Ethan Mick

Outputting a Postgres Table as JSON

I have a Postgres table and I want to output its contents as JSON so I can have a .json file for some tests. Turns out, this is pretty easy. Let's say the table name is users:

select array_to_json(array_agg(row_to_json(t)))
from (
SELECT * FROM users
) t

And done. That will output the entire users table (everything that matches the SELECT query) to a JSON array that you can just drop into a file.

Be the best web developer you can be.

A weekly email on Next.js, React, TypeScript, Tailwind CSS, and web development.

No spam. Unsubscribe any time.