Flask jsonify print results on new lines

丶灬走出姿态 提交于 2021-02-10 06:10:34

问题


First time using Flask, I have created a very basic app and I am trying to print the results of a recommender system. The first set of code is from my python function (print_most_similar) and is creating a formatted string in hopes to print every REC on a new line. The second section of code is obviously my flask routing. You can see that the flask part calls the function, so it is returned 'y'. I believe the jsonify will not take the \n characters. I have tried using just '\n' in the string formatting, but it just appears as a string. As does '\t'.

for k in range(len(sugg)):
    x = str("REC {}: {}\\n".format(k+1, sugg[k]))
    y += x
return y

@app.route("/getrecomm",methods=['GET','POST'])
def getrecomm():
    restname = request.args.get('restname', type=str)
    number = request.args.get('number', type=int)
    i = getBusIndex(restname, names)
return make_response(jsonify(result=(print_most_similar(rating, names, i, number))),200)

Currently, the results print like this: REC 1: Harbor House Cafe & Lounge\nREC 2: Starbucks\nREC 3: McDonald's\nREC 4: Taco Bell\nREC 5: Panda Express\n

I would like them to print like this: REC 1: Harbor House Cafe & Lounge REC 2: Starbucks REC 3: McDonald's REC 4: Taco Bell REC 5: Panda Express

I'm using python 3, fyi. Any suggestions would be super appreciated!


回答1:


Summary

  • Answer: <br>
  • Alternative: JSONView Chrome Extension

The only one that give me good results was <br>:

Example

from flask import Flask, jsonify

app = Flask(__name__)

tasks = [
    {
        '<br>id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 
        'done': False
    },
    {
        '<br>id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web', 
        'done': False
    }
]

@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

if __name__ == '__main__':
    app.run(debug=True)

In your browser the <br> character will be rendered as html and reproduce a new line.

Result: "creates" new lines in json

Jsonify can't help you because it takes the values (integer,boolean,float, etc) as a string and avoid special characters like \n, \t, etc

Finally, if you just want a fancy way to visualize json files in your browser, you could use JSONView, is a Chrome extension that render Json files in a more understandable way, like this.

rendering with JSONView



来源:https://stackoverflow.com/questions/44349546/flask-jsonify-print-results-on-new-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!