Last active
December 7, 2017 13:55
-
-
Save rwoody/2f2fbc56ceb0b5cfe2b7a59c7a7b73d4 to your computer and use it in GitHub Desktop.
PostgreSQL - Queries returned as JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 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; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 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