json.dumps vs flask.jsonify [英] json.dumps vs flask.jsonify

查看:132
本文介绍了json.dumps vs 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的结果。转储返回。我在做什么错了?

解决方案 flask会返回 flask.Response()对象,该对象已经具有用于json响应的适当的内容类型头application / json,而 json .dumps()将只返回一个编码的字符串,这将需要手动添加MIME类型的头。



查看更多关于 jsonify()函数 here
$ b 编辑:
另外,我注意到 jsonify()处理kwargs或dictionaries,而 json.dumps()还支持列表和其他。


I am not sure I understand the purpose of flask.jsonify method. I try to make 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 result that looks more like what json.dumps returns. What am I doing wrong?

解决方案

The jsonify() function in flask returns flask.Response() object that already has the appropriate content-type header 'application/json' for use with json responses, whereas the json.dumps() 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.

这篇关于json.dumps vs flask.jsonify的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆