我正在使用 Bottle 编写 API ,到目前为止,这太棒了。但是,在尝试返回 JSON 数组时遇到了一个小障碍。这是我的测试应用代码:
from bottle import route, run
@route('/single')
def returnsingle():
return { "id": 1, "name": "Test Item 1" }
@route('/containsarray')
def returncontainsarray():
return { "items": [{ "id": 1, "name": "Test Item 1" }, { "id": 2, "name": "Test Item 2" }] }
@route('/array')
def returnarray():
return [{ "id": 1, "name": "Test Item 1" }, { "id": 2, "name": "Test Item 2" }]
run(host='localhost', port=8080, debug=True, reloader=True)
当我运行它并请求每个路由时,我会从前两个路由中得到我期望的 JSON 响应:
/single
{ id: 1, name: "Test Item 1" }
/containsarray
{ "items": [ { "id": 1, "name": "Test Item 1" }, { "id": 2, "name": "Test Item 2" } ] }
所以,我希望返回一个字典列表来创建以下 JSON 响应:
[ { "id": 1, "name": "Test Object 1" }, { "id": 2, "name": "Test Object 2" } ]
但是请求 /array
路由只会导致错误。我做错了什么,如何以这种方式返回 JSON 数组?
最佳答案
Bottle 的 JSON 插件只希望返回字典,而不是数组。存在与返回 JSON 数组相关的漏洞 - 参见示例 this post about JSON hijacking .
如果你真的需要这样做,可以这样做,例如
@route('/array')
def returnarray():
from bottle import response
from json import dumps
rv = [{ "id": 1, "name": "Test Item 1" }, { "id": 2, "name": "Test Item 2" }]
response.content_type = 'application/json'
return dumps(rv)
关于python - 如何使用 Bottle 返回 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12293979/