【发布时间】:2017-03-01 04:50:09
【问题描述】:
我有一个从 mysql 选择查询接收数据的 Python API。数据如下所示:
| 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"}
【问题讨论】:
-
您必须在客户端自己解析 json 字符串,例如,如果它是 python 客户端,请执行 json.loads。
-
通过调用
json.loads(my_string)来实现json.dumps(my_obj)的逆运算 -
>>> x=[90, 1, "a"] >>> d={'val':x[0],'type':x[1],'status':x[2]} >>> json.dumps(d) '{"status": "a", "type": 1, "val": 90}'
标签: python mysql json rest python-3.x