我有一个Python,它接收来自mysql select查询的数据。数据如下:
| val | type | status |
|-----|------|--------|
| 90 | 1 | a |该数据在python中得到了很好的接受。现在,我想将这些数据以JSON的形式呈现给我的REST客户端--怎么做?
下面是我的python代码:
def somefunction(self, by, identifier):
# validate args
procedure = 'mysproc' + str(by)
try:
with self.connection.cursor() as cursor:
cursor.callproc(procedure,[str(identifier)])
self.connection.commit()
result = cursor.fetchone()
print("+++ Result: " + str(result) + " +++")
except:
result = "Request Failed"
raise
finally:
self.DestroyConnection()
return json.dumps(result)有了这个,我的当事人收到了:
"[90, 1, "a"]"问题:
有什么方法可以让我把它作为一个合适的JSON来接收吗?像这样:
{'val': 90, 'type': 1 , : 'status': "a"}发布于 2016-10-19 18:27:58
您首先需要获得mysql查询,以返回dict对象而不是列表。如果您的库是MySQLdb,那么这个答案是:Python - mysqlDB, sqlite result as dictionary是您所需要的。
下面是指向MySQLdb:http://www.mikusa.com/python-mysql-docs/docs/MySQLdb.connections.html文档的链接
我认为,如果传入要在创建游标时使用的游标类,则获取的结果将是字典。
with self.connection.cursor(MySQLdb.cursors.DictCursor) as cursor:在字典上运行json.dumps(结果)将给出您想要的输出。
https://stackoverflow.com/questions/40133216
复制相似问题