gpt4 book ai didi

jquery - 从 Flask 返回字典列表到 Ajax/Jquery

转载 作者:行者123 更新时间:2023-12-01 01:41:53 25 4
gpt4 key购买 nike

我希望 Flask 返回一个字典列表,其中每个字典具有以下结构:

{'category': 'Spas/beauty/personal care', 'location': [48.84014, 2.26351], 'id': '161608194188848', 'zip': 'Tel:0777034152', 'state': '', '_id': ObjectId('57a9a8582daf236574089796'), 'street': '166 avenue de Versailles', 'category_list': [{'name': 'Aesthetics', 'id': '146053955462002'}], 'name': 'The bar à sourcils', 'city': 'Paris', 'country': 'France'}

我尝试了很多种方法,遇到的主要错误信息是:

  • “dict”对象没有属性“serialize”:当我尝试序列化列表中的字典时。
  • ObjectId(...) 不可 JSON 序列化:当我尝试使用 JSONIFY 或 json.dumps() 时。

这是 flask 代码:

@app.route('/getme', methods=['POST'])
def receiveData():
curPos = request.json # curPos = {'lat': , 'lng': }
client = MongoClient()
db = client.places
fbplacesCollection = db.fbplaces
query = {'location': {'$geoWithin': {'$center': [[curPos['lat'], curPos['lng']], 0.089992801]}}}
result = list(fbplacesCollection.find(query))
return ' ' # I want to send the list called result

这是 Ajax/Jquery 代码:

$.ajax({
method: "POST",
url: "getme",
contentType:"application/json",
dataType:"json",
data: JSON.stringify(toSend)
})
.done(function( msg ) {
// do s.th with the received msg
console.log(msg);
});

任何帮助将不胜感激。

最佳答案

我找到了解决方案:

将以下内容添加到 flask 代码中:

from bson.json_util import dumps
...
dumps(result)
return (result)

注意:由于 MongoDB 将文档存储在 BSON 文件中,因此 json.dumps() 将不起作用。 json_util – 将 Python 的 json 模块与 BSON 文档结合使用的工具 – 将完成此类工作。请参阅http://api.mongodb.com/python/current/api/bson/json_util.html .

干杯!

关于jquery - 从 Flask 返回字典列表到 Ajax/Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38862102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com