json.dumps vs flask.jsonify
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.
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.
How to correctly use Flask's jsonify() to return json?
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
Pretty Display JSON data from with Flask
Use json.dumps
response = json.dumps(response.text, sort_keys = False, indent = 2)
or to make it prettier
response = json.dumps(response.text, sort_keys = True, indent = 4, separators = (',', ': '))
Template
#results.html
...
<div class="results">
<pre>{{ response }}</pre>
</div>
...
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.
Source: https://stackoverflow.com/a/13172658/264802
Why is flask's jsonify method slow?
My guess is: it has a lot to do with indentation and making a pretty
json dump. Here's the method definition (I stripped the comments to save space, full code can be found here) :
def jsonify(*args, **kwargs):
indent = None
separators = (',', ':')
if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr:
indent = 2
separators = (', ', ': ')
if args and kwargs:
raise TypeError('jsonify() behavior undefined when passed both args and kwargs')
elif len(args) == 1: # single args are passed directly to dumps()
data = args[0]
else:
data = args or kwargs
return current_app.response_class(
(dumps(data, indent=indent, separators=separators), '\n'),
mimetype=current_app.config['JSONIFY_MIMETYPE']
)
dumps
wraps simplejson.dumps
if the module is available, otherwise it uses json.dumps
.
Get Python Flask to return application/json using json.dumps
Change it like this:
from flask import Response
@app.route("/<arg1>")
def route1(arg1):
dict1 = {"prop1": "p1", "prop2": "p2"}
return Response(json.dumps(dict1), mimetype='application/json')
how to keep order of sorted dictionary passed to jsonify() function?
Add this config line to your code after the app definition:
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
Sending JSON and status code with a Flask response
Use flask.jsonify()
. This method takes any serializable data type. For example I have used a dictionary data
in the following example.
from flask import jsonify
@app.route('/login', methods=['POST'])
def login():
data = {'name': 'nabin khadka'}
return jsonify(data)
To return a status code, return a tuple of the response and code:
return jsonify(data), 200
Note that 200 is the default status code, so it's not necessary to specify that code.
UPDATE
As of Flask 1.1, the return statement will automatically jsonify
a dictionary in the first return value. You can return the data directly:
return data
You can also return it with a status code:
return data, 200
Minified JSON in flask's jsonify()
Simply set the configuration key JSONIFY_PRETTYPRINT_REGULAR
to False
- Flask pretty-prints JSON unless it is requested by an AJAX request (by default).
Flask jsonify returns bytes and string instead of json object
Hey you can solve this issue with the json library.
Example:
import json
def post_new_cafe():
new_cafe = Cafe(
name=request.form.get('name'),
map_url=request.form.get('map_url'),
img_url=request.form.get('img_url'),
location=request.form.get('location'),
seats=request.form.get('seats'),
has_toilet=bool(strtobool(request.form.get('has_toilet'))),
has_wifi=bool(strtobool(request.form.get('has_wifi'))),
has_sockets=bool(strtobool(request.form.get('has_sockets'))),
can_take_calls=bool(strtobool(request.form.get('can_take_calls'))),
coffee_price=request.form.get('coffee_price')
)
return json.dumps({"success": "Succesfully added the new cafe."})
response = post_new_cafe()
data = json.loads(response)
print(data)
print(data["success"])
For more information look at the Documentation about JSON
If you need to serialize a numpy array, there is a question on how to serialize a numpy array as JSON
Regarding your other issue:
@app.route('/add_form', methods=['GET', 'POST'])
def add_new_cafe_form():
form = CafeForm()
if form.validate_on_submit():
response = post_new_cafe()
print(response.json())
return render_template("add.html", form=form)
You need to convert the response from binary to string first: response.decode('utf-8')
and then parse it as JSON: json.loads(response.decode('utf-8'))
How do I convert a JSON Response object (jsonify from flask) to a dictionary to process
Just solved it!
using json.loads(json.dumps(response)
This dumps the request as a string and then converts into the required json object!
Related Topics
List VS Generator Comprehension Speed with Join Function
Differencebetween 'Same' and 'Valid' Padding in Tf.Nn.Max_Pool of Tensorflow
How to Trim Whitespace from a String
Returning the Product of a List
Isprime Function for Python Language
How to Expand a List to Function Arguments in Python
Matplotlib Colorbar for Scatter
Intersection of Two Graphs in Python, Find the X Value
Appending Pandas Dataframes Generated in a for Loop
Django Filefield with Upload_To Determined at Runtime
Pylint "Unable to Import" Error - How to Set Pythonpath
How to Pass a Method as a Parameter in Python
How to Check a String for Specific Characters
Read File Data Without Saving It in Flask
Add a String Prefix to Each Value in a String Column Using Pandas