如何正确使用Flask的jsonify()来返回json? [英] How to correctly use Flask's jsonify() to return json?

查看:2648
本文介绍了如何正确使用Flask的jsonify()来返回json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用flask.jsonify函数从字典输入中输出格式化的json响应时遇到了一些问题,如

我的代码似乎是返回Response对象,而不是格式化的json对象
$ b 我有

  @ app.route( '/ rparser',methods = ['GET','POST'])
def rparser():
form = ParserForm(request.form)
request.method =='POST ':
result = jsonify(** dict)
return render_template('rparser.html',form = form,result = result)
else:
return render_template('rparser .html',form = form)

其中dict是调用函数返回的字典对象。 / p>

在我的模板中,我有:

 

{%如果结果%}
{{result}}
{%endif%}

显示:


回复135 bytes [200 OK]

我将这个返回json表示,我正在寻找?

您可以使用json.dumps像这样:
$ $ $

$ b $返回render_template(
'index.html',
title ='主页',
result = json.dumps({a:[{o:1},{o:2}]] },sort_keys = False,indent = 2)

像这样的模板:

$ $ p $ code如果结果%$
预先{{结果}}
预>
{%endif%}

如果这符合您的预期。我认为jsonify用于提供http.response数据,而不是模板的上下文数据。



查看jsonify: https://stackoverflow.com/a/13172658/1307985


I'm having a little trouble using the flask.jsonify function to output a formatted json response from a dictionary input, as described in here.

My code is seems to be returning the Response object, instead of the formatted json object that I want.

I have

@app.route('/rparser', methods=['GET', 'POST'])
def rparser():
    form = ParserForm(request.form)
    if request.method=='POST':
        result = jsonify(**dict)
        return render_template('rparser.html', form=form, result=result)
    else:
        return render_template('rparser.html', form=form)

where dict is a dictionary object returned from calling a function.

And in my template, I have:

(form up here)

{% if result %}
    {{ result }}
{% endif %}

This is displaying:

Response 135 bytes [200 OK]

How would I make this return the json representation that I am looking for?

解决方案

You can use json.dumps like so:

@app.route('/')
def home():
return render_template(
    'index.html',
    title='Home Page',
    result=json.dumps({"a":[{"o":1},{"o":2}]}, sort_keys = False, indent = 2)
)

and just format it in the template like so:

{% if result %}
   <pre>{{ result }}</pre>
{% endif %}

If this fits to your expectations. I think that jsonify is used to provide http.response data, not context data for templates.

Have a look here for jsonify: https://stackoverflow.com/a/13172658/1307985

这篇关于如何正确使用Flask的jsonify()来返回json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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