简体   繁体   中英

return empty JSON by Flask

I have a simple functions, which should returns JSON.

@app.route('/storage/experiments', methods=['GET'])
def get_experiments():
    if not request.json:
        abort(400)
    experiments = db['experiments']
    cursor = experiments.find(request.get_json())
    print(dumps(cursor))
    resp = Response(response=dumps(cursor),
    status=200, \
    mimetype="application/json")
    return resp

print(dumps(cursor)) shows

[{"current": "11", "date": "12.12.2001", "_id": {"$oid": "551c7b642349c517f5fa5223"}, "name": "xaxa", "voltage": "34"}]

but returns empty brackets []

you can use the jsonify function from the flask module.

Edit Chrisitian is right I didn't notice that you were using a list. Anyways here's a decorator that I wrote exactly to solve this problem: Json decorator . Hope this helps.

I guess this is happneing because your database cursor (I don't know what database framework you use. sqlalchemy ?) points at the end of your dataset when you want to return it, because your print() -statement was already iterating over it. It should work with this code when you just comment out the print() statement, because I can't see any other error in this code:

@app.route('/storage/experiments', methods=['GET'])
def get_experiments():
    if not request.json:
        abort(400)
    experiments = db['experiments']
    cursor = experiments.find(request.get_json())
    #print(dumps(cursor))
    resp = Response(response=dumps(cursor),
    status=200, \
    mimetype="application/json")
    return resp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM