将sql结果转换为可序列化的JSON

时间:2019-05-26 06:38:48

标签: python postgresql sqlalchemy

我使用python。我创建了一个云函数,以从与PostgreSQL连接的搜索查询中返回结果。我发誓SQL是连接。当谈到从sql重新调整获取结果时,它说行对象不是JSON可序列化的。我应该如何将此行结果转换为json?

这是我的代码

def freebie(request):


  engine = create_engine('postgresql://ABC' , echo=True)

  conn = engine.connect()

  x_sql = sa.text('''
            SELECT user_label from "database"."user"
            WHERE "_id" = :userId
        ''')

  record = conn.execute(x_sql, userId = '82f3f82f-5bae-45d3-971f-b4af3a06182f', 
            current_time = datetime.now(), ).fetchall()

  user_labbel = record[0][0]

  campaign_sql = sa.text('''
            SELECT * from "database"."user_fav_books"
            WHERE "user_label" = :campaign_id
        ''')

  result = conn.execute(campaign_sql, campaign_id = user_labbel, 
            current_time = datetime.now(), ).fetchall()

  if len(result) == 0 :
    return "No result"
  else:
    return json.dump(result, indent=4 , check_circular=True)

2 个答案:

答案 0 :(得分:0)

尝试一下

import json

然后返回如下图所示,

return json.dumps(results, indent=4)

答案 1 :(得分:0)

您可以将结果中的每一行转换为字典,然后序列化为json。请注意,您无需在连接结果上调用fetchall

result = conn.execute(campaign_sql, campaign_id = user_labbel, 
          current_time = datetime.now(), )
dicts = [dict(row) for row in result]
j = json.dumps(dicts)