json.dumps vs flask.jsonify(json.dumps 与 flask.jsonify)
问题描述
我不确定我是否理解 flask.jsonify 方法的目的.我尝试从中创建一个 JSON 字符串:
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}
但是我使用 json.dumps 得到的结果与使用 flask.jsonify 得到的不同.
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":…}
显然我需要得到一个看起来更像 json.dumps 返回的结果.我做错了什么?
Obviously I need to get a result that looks more like what json.dumps returns. What am I doing wrong?
推荐答案
flask 中的 jsonify() 函数返回一个 flask.Response() 对象,该对象已经有了与 json 响应一起使用的适当的内容类型标头application/json".而 json.dumps() 方法只会返回一个编码字符串,这需要手动添加 MIME 类型标头.
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.
查看更多关于 jsonify() 函数的信息这里 供完整参考.
See more about the jsonify() function here for full reference.
另外,我注意到 jsonify() 处理 kwargs 或字典,而 json.dumps() 还支持列表和其他.
Also, I've noticed that jsonify() handles kwargs or dictionaries, while json.dumps() additionally supports lists and others.
这篇关于json.dumps 与 flask.jsonify的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:json.dumps 与 flask.jsonify
基础教程推荐
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
