我如何在 Flask 中`jsonify` 一个列表? [英] How do I `jsonify` a list in Flask?

查看:30
本文介绍了我如何在 Flask 中`jsonify` 一个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前 Flask 在对列表进行 jsonifying 时会引发错误.

我知道可能有安全原因https://github.com/mitsuhiko/flask/issues/170,但我仍然希望有一种方法可以返回如下所示的 JSON 列表:

<预><代码>[{'a':1,'b':2},{'a':5,'b':10}]

代替

{ '结果': [{'a':1,'b':2},{'a':5,'b':10}]}

响应 application/json 请求.如何使用 Jsonify 在 Flask 中返回 JSON 列表?

解决方案

jsonify 阻止您在 Flask 0.10 及更低版本中执行此操作 出于安全原因.

无论如何,只需使用 Python 标准库中的 json.dumps 即可.

http://docs.python.org/library/json.html#json.dumps

Currently Flask would raise an error when jsonifying a list.

I know there could be security reasons https://github.com/mitsuhiko/flask/issues/170, but I still would like to have a way to return a JSON list like the following:

[
    {'a': 1, 'b': 2},
    {'a': 5, 'b': 10}
]

instead of

{ 'results': [
    {'a': 1, 'b': 2},
    {'a': 5, 'b': 10}
]}

on responding to a application/json request. How can I return a JSON list in Flask using Jsonify?

解决方案

jsonify prevents you from doing this in Flask 0.10 and lower for security reasons.

To do it anyway, just use json.dumps in the Python standard library.

http://docs.python.org/library/json.html#json.dumps

这篇关于我如何在 Flask 中`jsonify` 一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆