Postgres SQL查询,它将对关联数组中的字段进行分组

时间:2017-04-06 16:06:00

标签: sql arrays json postgresql psycopg2

示例:我有桌子"门票"

id, int
client_id, int
client_name, text

而不是通常的选择(" SELECT id,client_id,client_name FROM ticket")我需要一些能够提供结果的东西:

{
    "id": 2,
    "client": {
        "id": 31,
        "name": "Mark"
    }
}

1 个答案:

答案 0 :(得分:1)

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}