简体   繁体   English

json.dumps 与flask.jsonify

[英]json.dumps vs flask.jsonify

I am not sure I understand the purpose of the flask.jsonify method.我不确定我是否理解flask.jsonify方法的目的。 I try to make a JSON string from this:我尝试从中制作一个 JSON 字符串:

data = {"id": str(album.id), "title": album.title}

but what I get with json.dumps differs from what I get with flask.jsonify .但我得到什么用json.dumps从我用得到不同flask.jsonify

json.dumps(data): [{"id": "4ea856fd6506ae0db42702dd", "title": "Business"}]
flask.jsonify(data): {"id":…, "title":…}

Obviously I need to get a result that looks more like what json.dumps returns.显然我需要得到一个看起来更像json.dumps返回的结果。 What am I doing wrong?我究竟做错了什么?

The jsonify() function in flask returns a flask.Response() object that already has the appropriate content-type header 'application/json' for use with json responses. jsonify()函数返回一个flask.Response()对象,该对象已经具有适当的内容类型标头 'application/json' 用于 json 响应。 Whereas, the json.dumps() method will just return an encoded string, which would require manually adding the MIME type header.json.dumps()方法只会返回一个编码字符串,这需要手动添加 MIME 类型标头。

See more about the jsonify() function here for full reference.在此处查看有关jsonify()函数的更多信息以获取完整参考。

Edit: Also, I've noticed that jsonify() handles kwargs or dictionaries, while json.dumps() additionally supports lists and others.编辑:另外,我注意到jsonify()处理 kwargs 或字典,而json.dumps()还支持列表和其他。

You can do:你可以做:

flask.jsonify(**data)

or或者

flask.jsonify(id=str(album.id), title=album.title)

This is flask.jsonify()这是flask.jsonify()

def jsonify(*args, **kwargs):
    if __debug__:
        _assert_have_json()
    return current_app.response_class(json.dumps(dict(*args, **kwargs),
        indent=None if request.is_xhr else 2), mimetype='application/json')

The json module used is either simplejson or json in that order.使用的json模块simplejson顺序是simplejsonjson current_app is a reference to the Flask() object ie your application. current_app是对Flask()对象的引用,即您的应用程序。 response_class() is a reference to the Response() class. response_class()是对Response()类的引用。

The choice of one or another depends on what you intend to do.选择一个或另一个取决于您打算做什么。 From what I do understand:根据我的理解:

  • jsonify would be useful when you are building an API someone would query and expect json in return.当您构建 API 时, jsonify会很有用,有人会查询并期望 json 作为回报。 Eg: The REST github API could use this method to answer your request.例如:REST github API 可以使用此方法来回答您的请求。

  • dumps , is more about formating data/python object into json and work on it inside your application. dumps ,更多是关于将数据/python 对象格式化为 json 并在您的应用程序中处理它。 For instance, I need to pass an object to my representation layer where some javascript will display graph.例如,我需要将一个对象传递给我的表示层,其中一些 javascript 将显示图形。 You'll feed javascript with the Json generated by dumps.您将使用转储生成的 Json 提供 javascript。

consider考虑

data={'fld':'hello'}

now现在

jsonify(data)

will yield {'fld':'hello'} and将产生 {'fld':'hello'} 和

json.dumps(data)

gives

"<html><body><p>{'fld':'hello'}</p></body></html>"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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