0

It appears that this works:

@app.route('/my/route/')
def my_route():
    return {
        'Something': True,
        'Else': None,
        'Thingy': 12345,
        'Blah': 'Blah'
    }

When I visit the route in a browser, I get valid JSON like this:

{
    "Something": true, 
    "Else": null, 
    "Thingy": 12345
    "Blah": "Blah", 
}

Everything is converted to valid JSON, but I haven't seen any documentation supporting this. I'm not even importing the jsonify module. Is this ok?

Glenn
  • 4,195
  • 9
  • 33
  • 41
  • 2
    In current, vanilla versions of Flask this does not seem to be valid. It results in a TypeError and "The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a dict." – jarmod Aug 13 '19 at 01:33
  • @jarmod I think I'm using vanilla Flask. I'm not sure how it's returning the JSON in this case. I did it by accident really. – Glenn Aug 13 '19 at 01:36
  • 1
    Typically you would import jsonify, and then return jsonify({...}). – jarmod Aug 13 '19 at 01:40

2 Answers2

2

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

Code:

from flask import Flask, render_template, json

app = Flask(__name__)

@app.route("/")
def index():
    return {
        'Something': True,
        'Else': None,
        'Thingy': 12345,
        'Blah': 'Blah'
    }

Output:

TypeError
TypeError: 'dict' object is not callable
The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a dict.

Screenshot:

showing error for returning dictionary

As the traceback indicates route's return type must be a string, tuple, Response instance, or WSGI callable.

arshovon
  • 13,270
  • 9
  • 51
  • 69
  • 2
    As of Flask `1.1.0` you can return a dictionary, or still use `jsonify()` for other data types. See [this answer](https://stackoverflow.com/a/58917715/2052575) and [these docs](https://flask.palletsprojects.com/en/1.1.x/quickstart/#apis-with-json). – v25 Nov 23 '19 at 23:06
0

define the custom json encoder! it will do the trick!

import flask
import datetime

app = flask.Flask(__name__)

class CustomJSONEncoder(flask.json.JSONEncoder):
    def default(self, obj):
        if   isinstance(obj, datetime.date): return obj.isoformat()
        try:
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return tuple(iterable)

        return flask.json.JSONEncoder.default(self, obj)

app.json_encoder = CustomJSONEncoder
rho
  • 771
  • 9
  • 24