Skip to content

Instantly share code, notes, and snippets.

@rwoody
Last active December 7, 2017 13:55
Show Gist options
  • Save rwoody/2f2fbc56ceb0b5cfe2b7a59c7a7b73d4 to your computer and use it in GitHub Desktop.
Save rwoody/2f2fbc56ceb0b5cfe2b7a59c7a7b73d4 to your computer and use it in GitHub Desktop.
PostgreSQL - Queries returned as JSON
; Outputs 1 json row per line.
; Eg.:
; {"foo": "bar"}
; {"baz": "qux"}
copy (
select row_to_json(t)
from (select * from users) t
) to '/Users/ryan/Desktop/users.json';
------ Other modifications ------
-- src: https://hashrocket.com/blog/posts/faster-json-generation-with-postgresql
-- Select specific rows:
select row_to_json(t)
from (
select id, text from words
) t;
-- More complex:
select row_to_json(t)
from (
select text, pronunciation,
(
select array_to_json(array_agg(row_to_json(d)))
from (
select part_of_speech, body
from definitions
where word_id=words.id
order by position asc
) d
) as definitions
from words
where text = 'autumn'
) t;
; Outputs array of json objects
; Eg.:
; [{"foo": "bar"},{baz": "qux"}]
COPY (SELECT array_to_json(array_agg(row_to_json(t)))
FROM (SELECT * FROM users) t) TO '/Users/ryan/Desktop/users.json';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment