Python Flask返回带有反斜杠的JSON卷曲请求

时间:2014-10-29 08:00:14

标签: json mongodb curl flask

我从我的mongoDB数据库中获取结果并尝试通过curl将它们作为JSON对象发送:

custos = customerDB.CustomerModel.find()

jsonCusto = []
for doc in custos:
temp = json.dumps(doc, default=json_util.default)
jsonCusto.append(temp)

我在发送之前打印并获取:

'{"firstName": "Joshu", "lastName": "Wak", "creation": {"$date": 1414531609314}, "Cust_ID": 101, "streetNo": "3231", "_id": {"$oid": "54500a19d0f6120a0021c879"}, "email": "lolazo@cvn.com", "streetName": "washingoton"}'

但在卷曲屏幕上,我得到了:

"{\"firstName\": \"Joshu\", \"lastName\": \"Wak\", \"creation\": {\"$date\": 1414531609314}, \"Cust_ID\": 101, \"streetNo\": \"3231\", \"_id\": {\"$oid\": \"54500a19d0f6120a0021c879\"}, \"email\": \"lolazo@cvn.com\", \"streetName\": \"washingoton\"}

我尝试了大约10种组合但无法正确使用。我将不胜感激任何帮助。

谢谢!

2 个答案:

答案 0 :(得分:3)

您几乎肯定会对您的JSON进行双重编码。只需删除循环中的json.dumps,只在最后使用它:

custos = customerDB.CustomerModel.find()
jsonCusto = list(custos)
jsonText = json.dumps(jsonCusto, default=json_util.default)

答案 1 :(得分:0)

我也遇到了同样的挑战。就我而言,我写了some_schema。 dumps()而不是some_schema。 dump()

下面是author_schema的输出。 dumps()

NAME   | HEARTS in this season
Thomas | 5
Dave   | 3
Erick  | 1

输出:

@app.route('/authors', methods = ['GET'])
def index():
    get_authors = Authors.query.all()
    author_schema = AuthorsSchema(many=True)
    authors= author_schema.dump(get_authors)
    return make_response(jsonify({"authors": authors}))

下面是author_schema的输出。 dump()

{
  "authors": "[{\"specialisation\": \"Joke Developer\", \"name\": \"Kaunda Ibn Ahmed\", \"id\": 1.0}, {\"specialisation\": \"History\", \"name\": \"Akademic Vuvuzela\", \"id\": 2.0}]"
}

输出:

@app.route('/authors', methods = ['GET'])
def index():
    .....
    .....
    authors= author_schema.dump(get_authors)
    return make_response(jsonify({"authors": authors}))
相关问题