如果由於某種原因,你需要爲忽略flask.jsonify
(添加例如自定義編碼器),你可以用它實現提到的安全修補程序@phpmycoder下面的方法做:
from json import dumps
from flask import make_response
def jsonify(status=200, indent=4, sort_keys=True, **kwargs):
response = make_response(dumps(dict(**kwargs), indent=indent, sort_keys=sort_keys))
response.headers['Content-Type'] = 'application/json; charset=utf-8'
response.headers['mimetype'] = 'application/json'
response.status_code = status
return response
app.route('/<major>/')
def major_res(major):
course = client.db.course_col.find({"major": (major.encode("utf8", "ignore").upper())})
return jsonify(**course)
app.route('/test/')
def test():
return jsonify(indent=2, sort_keys=False, result="This is just a test")
響應:
{
"course": "CSCI052",
"description": "Fundamentals of Computer Science. A solid foundation in functional programming, procedural and data abstraction, recursion and problem-solving. Applications to key areas of computer science, including algorithms and complexity, computer architecture and organization, programming languages, finite automata and computability. This course serves the same role as HM 60 as a prerequisite for upper-division computer science courses at any of the Claremont Colleges. Prerequisite: 51.",
"instructor": "Bull, Everett L.,, Jr.",
"name": " Fundamentals of Computer Science",
"number": 52,
"school": "PO"
}
見我other answer使用自定義JSON編碼器
對於這種使用''json.dimps'參數indent'一個例子,但你已經擁有它。這不是縮小JSON,因爲在逗號和':'後面有空格。那麼你如何得到這個輸出(在瀏覽器中,日誌/打印,wget)呢?可能你需要使用'return Response(,mimetype ='application/json')'或'flask.jsonofy'和'indent'參數。 –
tbicr