If you like to use SQL for this, there is json_build_object function:
SELECT
json_build_object(
'id', id,
'client', json_build_object(
'id', client_id,
'name', client_name))
FROM
tickets;
Example:
#!/usr/bin/env python
import psycopg2
import json
conn = psycopg2.connect('')
cur = conn.cursor()
cur.execute("""
with tickets(id, client_id, client_name) as (values(1,2,'x'),(3,4,'y'))
SELECT
json_build_object(
'id', id,
'client', json_build_object(
'id', client_id,
'name', client_name))
FROM
tickets;
""")
for row in cur.fetchall():
print row, json.dumps(row[0])
Output:
({u'client': {u'id': 2, u'name': u'x'}, u'id': 1},) {"client": {"id": 2, "name": "x"}, "id": 1}
({u'client': {u'id': 4, u'name': u'y'}, u'id': 3},) {"client": {"id": 4, "name": "y"}, "id": 3}