Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

python - How to correctly use Flask's jsonify() to return json?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...