将sql表数据转换为json

时间:2016-11-18 06:54:24

标签: python sql json

我在服务器端使用烧瓶,我有以下api:

class DateTimeEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return o.isoformat()

        return json.JSONEncoder.default(self, o)


@app.route('/getTransaction', methods=['GET','POST'])
def getTransaction():

uid = request.form["uid"]
db = my.connect("somehost.com","someuser","somepwd","someDB")
cur = db.cursor()

cur.execute("select * from Transactions where uid='%s'" %(uid))

json_string = json.dumps(cur.fetchall(),cls=DateTimeEncoder)

db.close()
return json.dumps(json_string)

在此之后我得到回复:

http://sairav.pythonanywhere.com/getTransaction

有没有办法可以用json格式转换这些数据(如名称,描述,金额,类型,id,时间,你可以在响应中看到的值)

json数组中的必需格式:

{"data":[
    {"Name":"John", "desc":"Doe","amount":"123.0","type":"credit","uid":"213","time":"12-11-2016 12:23:22"},
    {"Name":"John2", "desc":"Doe","amount":"1234.0","type":"credit","uid":"213","time":"12-11-2016 12:23:22"},
    {"Name":"John3", "desc":"Doe","amount":"1235.0","type":"credit","uid":"213","time":"12-11-2016 12:23:22"},
]}

1 个答案:

答案 0 :(得分:1)

在这里找到了真正帮助answer这完全解决了我的目的,它将我的表列名设置为json数组中json对象的键。 感谢algrebe的链接。

我运行的代码包含所需的json输出:

  @app.route('/getTransaction', methods=['GET','POST'])
  def getTransaction():

  uid = request.form["uid"]
  db = my.connect("somehost.com","someuser","somepwd","someDB")
  cur = db.cursor()

  cur.execute("select * from Transactions where uid='%s'" %(uid))


  **columns = cur.description
  result = [{columns[index][0]:column for index, column in enumerate(value)}   for value in cur.fetchall()]**


  db.close()

  **return json.dumps(result,cls=DateTimeEncoder)**