Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kracekumar
Last active July 13, 2021 12:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kracekumar/2d1d0b468cafa5197f5e21734047c46d to your computer and use it in GitHub Desktop.
Save kracekumar/2d1d0b468cafa5197f5e21734047c46d to your computer and use it in GitHub Desktop.
krace@hotbox /m/u/code> cat json_pg.py
import psycopg2
def run(stmt):
cur = psycopg2.connect(database='test', user='postgres', password='password', host='localhost').cursor()
cur.execute(stmt)
result = cur.fetchall()
print(list(result))
stmt = 'select row_to_json(row) from (select book.id, book.name, book.author_id, author.name as author_name from book inner join author on book.author_id = author.id) row;'
run(stmt)
krace@hotbox /m/u/code> python json_pg.py
[({'id': 1, 'author_id': 1, 'name': 'War and Peace', 'author_name': 'Leo Tolstoy'},),
({'id': 2, 'author_id': 2, 'name': 'The Trial', 'author_name': 'Kafka'},),
({'id': 3, 'author_id': 2, 'name': 'The metamorphosis', 'author_name': 'Kafka'},)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment