【问题标题】:How to return JSON from Python REST API如何从 Python REST API 返回 JSON
【发布时间】: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


【解决方案1】:

您首先需要让 mysql 查询返回一个 dict 对象而不是一个列表。如果您的库是 MySQLdb,那么这个答案:Python - mysqlDB, sqlite result as dictionary 就是您所需要的。

这里是 MySQLdb 文档的链接:http://www.mikusa.com/python-mysql-docs/docs/MySQLdb.connections.html

我认为,如果您在创建游标时传入要使用的游标类,那么 fetchone 的结果将是一个字典。

with self.connection.cursor(MySQLdb.cursors.DictCursor) as cursor:

在字典上运行 json.dumps(result) 将给出您正在寻找的输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2021-01-31
    • 2018-08-11
    相关资源
    最近更新 更多