Python TypeError:**后面的jsonify()参数必须是映射,而不是使用Flask返回JSON的列表
我在和flask和gevent合作。我的函数如下所示:Python TypeError:**后面的jsonify()参数必须是映射,而不是使用Flask返回JSON的列表,python,json,flask,Python,Json,Flask,我在和flask和gevent合作。我的函数如下所示: @app.route('/index',methods=['POST']) def index(): .... .... gevent.joinall(threads) res = [t.value for t in threads] return jsonify(**res) 生成的响应(res)是一个字典列表,如下所示: [{u'token': u'146bf00b2cb96e6c425c2ab997637', u'a': u'aaa
@app.route('/index',methods=['POST'])
def index():
....
....
gevent.joinall(threads)
res = [t.value for t in threads]
return jsonify(**res)
生成的响应(res)是一个字典列表,如下所示:
[{u'token': u'146bf00b2cb96e6c425c2ab997637', u'a': u'aaa'},{u'token': u'146bf00b2cb96e6c425c2ab3f7417', u'a': u'bbb'}, {u'token': u'146bf00b2cb96e6c425c2ab3f5692', u'a': u'ccc'} ]
当我尝试将其具体化时,我得到:
TypeError: jsonify() argument after ** must be a mapping, not list
我做错了什么?(**res)
希望res
成为一个单独的字典,它可以扩展为jsonify
函数的关键字参数。乙二醇
res = dict(a=1, b=2)
jsonify(**res)
# is the same as
jsonify(a=1, b=2)
在您的情况下,您不仅可以做到:
jsonify(res)
编辑:事实上,我认为你需要把你的结果包装在一个dict中才能返回它们。您可以使用jsonify将其设置为快捷方式:
jsonify(results=res)
给你
{
"results": [
{
"a": "aaa",
"token": "146bf00b2cb96e6c425c2ab997637"
},
{
"a": "bbb",
"token": "146bf00b2cb96e6c425c2ab3f7417"
},
{
"a": "ccc",
"token": "146bf00b2cb96e6c425c2ab3f5692"
}
]
}
**
可用于dict而不是列表,不知道jsonify函数的作用,但您可以使用jsonify(*res)
或`jsonify(*res)`谢谢Padraic,*运算符的名称是什么,我可以查找它?我知道**,但不知道*再次感谢,这很有帮助!谢谢你,艾丹,真的很管用!我能问一下你在哪里找到jsonify(results=res)吗?很高兴它能帮上忙。在我开始使用python/flask之前,我一直使用dict作为我所做的任何基于json的服务的基本结构。因此,我通常会做一些类似于jsonify(objects=[obj1,obj])
——这只是习惯而已。