json.dumps与flask.jsonify

问题:json.dumps与flask.jsonify

我不确定我是否了解该flask.jsonify方法的目的。我尝试从中制作一个JSON字符串:

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

但是我得到的与我得到的json.dumps有所不同flask.jsonify

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

显然,我需要得到一个看起来更像json.dumps返回结果的结果。我究竟做错了什么?

I am not sure I understand the purpose of the flask.jsonify method. I try to make a JSON string from this:

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(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. What am I doing wrong?


回答 0

jsonify()flask中的函数返回一个flask.Response()对象,该对象已经具有用于json响应的适当的内容类型标头’application / json’。而该json.dumps()方法将仅返回编码后的字符串,这将需要手动添加MIME类型标头。

查看更多有关该jsonify()功能在这里完全参考。

编辑:另外,我注意到它可以jsonify()处理kwarg或字典,同时json.dumps()还支持列表和其他列表。

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. Whereas, the json.dumps() method will just return an encoded string, which would require manually adding the MIME type header.

See more about the jsonify() function here for full reference.

Edit: Also, I’ve noticed that jsonify() handles kwargs or dictionaries, while json.dumps() additionally supports lists and others.


回答 1

你可以做:

flask.jsonify(**data)

要么

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

You can do:

flask.jsonify(**data)

or

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

回答 2

这是 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')

json使用的模块是simplejsonjson顺序相同。current_app是对Flask()对象(即您的应用程序)的引用。response_class()是对该Response()类的引用。

This is 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. current_app is a reference to the Flask() object i.e. your application. response_class() is a reference to the Response() class.


回答 3

一个或另一个的选择取决于您打算做什么。据我了解:

  • 当您构建一个有人查询并期望json作为回报的API时,jsonify会很有用。例如:REST github API可以使用此方法来回答您的请求。

  • dumps,更多关于将数据/ python对象格式化为json并在您的应用程序中进行处理。例如,我需要将一个对象传递给我的表示层,其中一些javascript将显示图形。您将使用转储生成的Json喂javascript。

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. E.g: The REST github API could use this method to answer your request.

  • dumps, is more about formating data/python object into json and work on it inside your application. For instance, I need to pass an object to my representation layer where some javascript will display graph. You’ll feed javascript with the Json generated by dumps.


回答 4

考虑

data={'fld':'hello'}

现在

jsonify(data)

将产生{‘fld’:’hello’}并且

json.dumps(data)

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

consider

data={'fld':'hello'}

now

jsonify(data)

will yield {‘fld’:’hello’} and

json.dumps(data)

gives

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