以简洁的方式显示从Flask返回的JSON

时间:2013-06-04 02:32:39

标签: python json flask

我正在使用Flask创建API并具有以下代码:

@app.route('/<major>/')
def major_res(major):
    course_list = list(client.db.course_col.find({"major": (major.encode("utf8", "ignore").upper())}))
    return json.dumps(course_list, sort_keys=True, indent=4, default=json_util.default)

在浏览器中查看/csci/时,输出如下所示:

[{ "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" }]

如何返回此词典,以便每个键和值都在各自的位置?

2 个答案:

答案 0 :(得分:20)

Flask提供jsonify()作为方便:

from flask import jsonify

@app.route("/<major>/")
def major_res(major):
    course_list = list(client.db.course_col.find({"major": major.upper()}))
    return flask.jsonify(**course_list)

这将返回jsonify的args作为JSON表示,并且与您的代码不同,它将发送正确的Content-Type标题:application/json。请注意文档对格式的说法:

  

如果JSONIFY_PRETTYPRINT_REGULAR config参数设置为True或Flask应用程序正在调试模式下运行,则此函数的响应将被打印出来。压缩(不漂亮)格式化当前意味着没有缩进,分隔符后没有空格。

当处于调试模式时,响应将收到非漂亮的JSON。这应该不是问题,因为JavaScript消费的JSON不需要格式化(这只是通过线路发送的额外数据),并且大多数工具格式自己接收JSON。

如果您仍想使用json.dumps(),则可以通过current_app.response_class()返回Response来发送正确的mimetype。

from flask import json, current_app

@app.route("/<major>/")
def major_res(major):
    course_list = list(client.db.course_col.find({"major": major.upper() }))
    return current_app.response_class(json.dumps(course_list), mimetype="application/json")

有关差异的更多信息:


在Flask 1.0之前,JSON处理有些不同。 jsonify将尝试检测请求是否为AJAX,如果不是则返回漂亮的打印;这被删除,因为它不可靠。 jsonify仅允许dicts作为security reasons的顶级对象;这在现代浏览器中不再适用。

答案 1 :(得分:0)

如果由于某种原因你需要覆盖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"
}

有关使用自定义json编码器的示例,请参阅我的other answer