Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I `jsonify` a list in Flask? [duplicate]

Tags:

json

flask

Currently Flask would raise an error when jsonifying a list.

I know there could be security reasons https://github.com/mitsuhiko/flask/issues/170, but I still would like to have a way to return a JSON list like the following:

[     {'a': 1, 'b': 2},     {'a': 5, 'b': 10} ] 

instead of

{ 'results': [     {'a': 1, 'b': 2},     {'a': 5, 'b': 10} ]} 

on responding to a application/json request. How can I return a JSON list in Flask using Jsonify?

like image 843
hllau Avatar asked Sep 15 '12 07:09

hllau


People also ask

How do you Jsonify a list in Flask?

To jsonify a list of objects with Python Flask, we add a method in our object's class to return the object's contents as a dictionary. to create the Gene class that has the serialize method that returns the instance properties in a dictionary.

Does Flask automatically Jsonify?

No, returning a dict in Flask will not apply jsonify automatically. In fact, Flask route cannot return dictionary.

What does Jsonify do in Flask?

jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.

How do you Jsonify an array in Python?

Use json. dumps() to convert a list to a JSON array in Python. The dumps() function takes a list as an argument and returns a JSON String.


2 Answers

You can't but you can do it anyway like this. I needed this for jQuery-File-Upload

import json # get this object from flask import Response  #example data:      js = [ { "name" : filename, "size" : st.st_size ,          "url" : url_for('show', filename=filename)} ] #then do this     return Response(json.dumps(js),  mimetype='application/json') 
like image 153
mianos Avatar answered Sep 30 '22 09:09

mianos


jsonify prevents you from doing this in Flask 0.10 and lower for security reasons.

To do it anyway, just use json.dumps in the Python standard library.

http://docs.python.org/library/json.html#json.dumps

like image 27
FogleBird Avatar answered Sep 30 '22 09:09

FogleBird