Flask-JSON
raw JSON → 0.4.0 verified Fri May 01 auth: no python maintenance
Flask-JSON is a Flask extension that provides better JSON support, including automatic JSON serialization for object instances (via __json__() method), datetime objects, and arbitrary types. The current version is 0.4.0. Development appears to be in a maintenance state with no recent releases.
pip install flask-json Common errors
error ImportError: cannot import name 'Jsonify' from 'flask.ext.json' ↓
cause Using the deprecated flask.ext.json import path or the extension is not installed.
fix
Install flask-json with pip and use direct import:
from flask_json import Jsonify error TypeError: Object of type MyClass is not JSON serializable ↓
cause The object does not have a __json__() method, or Flask-JSON is not initialized properly.
fix
Add a __json__() method to your class that returns a dict. Also ensure you initialized FlaskJSON(app).
Warnings
gotcha Flask-JSON overrides Flask's default JSON encoder globally. If you need custom encoding for different parts of your app, be careful as the global override might affect other extensions or libraries. ↓
fix Consider using flask.jsonify() with custom JSONEncoder or using Flask-JSON's Jsonify only in specific routes but be aware of the global override.
gotcha The __json__() method must be defined on custom objects to be serialized. If the method is missing, Flask-JSON will fall back to Flask's default encoder, which may not handle the object correctly. ↓
fix Ensure all custom classes that need serialization implement a __json__() method returning a JSON-serializable dict.
deprecated As of Flask 2.3 and above, the `import flask.ext.json` path has been deprecated. Always use the direct import path: `from flask_json import ...` ↓
fix Use `from flask_json import FlaskJSON, Jsonify` instead of deprecated `flask.ext.json`.
Imports
- Jsonify
from flask_json import Jsonify - FlaskJSON
from flask_json import FlaskJSON
Quickstart
from flask import Flask
from flask_json import FlaskJSON, Jsonify
app = Flask(__name__)
json = FlaskJSON(app)
class MyObject:
def __init__(self, name):
self.name = name
def __json__(self):
return {'name': self.name}
@app.route('/')
def index():
return Jsonify(data=MyObject('test'))
if __name__ == '__main__':
app.run()