-1
我使用在服務器端的燒瓶,我有以下API:轉換SQL表中的數據JSON
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
有沒有一種方法,我可以用鍵(例如名稱,描述,數量,類型,ID,在響應中可以看到的值的時間)以json格式轉換此數據
需要的格式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"},
]}
默認光標是一個行光標即它發出'[ 「約翰」, 「DOE」, 「123.0」, 「信用」]'。您可以創建一個'dictcursor',它將以字典形式發出行。否則,您可以像訪問[this so answer](http://stackoverflow.com/a/5058950/1520594)一樣訪問'cursor.description',並用字段名稱壓縮該行。一旦你有了,你可以繼續使用json.dumps – algrebe