ImportError: cannot import name 'JSONEncoder' from 'flask.json'
Fixes `ImportError: cannot import name 'JSONEncoder' from 'flask.json'` in flask. Use when a Flask 2.2/2.3 upgrade breaks a custom JSON encoder imported from flask.json. Not for 'Object of type X is not JSON serializable' at runtime; that means the provider is fine but a type lacks a handler.
ImportError: cannot import name 'JSONEncoder' from 'flask.json'
TL;DR
Flask 2.2 deprecated and 2.3 removed flask.json.JSONEncoder. Subclass flask.json.provider.DefaultJSONProvider and override default() instead, then set it as app.jsonproviderclass. That is the supported way to customize JSON output now.
The error
ImportError: cannot import name 'JSONEncoder' from 'flask.json'Fix it
- Locate the custom encoder: grep -rn "JSONEncoder" --include=*.py .
Expected: Usually one class subclassing flask.json.JSONEncoder.
- Rewrite it as a provider: class MyProvider(DefaultJSONProvider): def default(self, obj): ... and set app.jsonproviderclass = MyProvider (or pass it via app.json).
Expected: Custom types serialize exactly as before.
- Delete the old import from flask.json. The provider import is from flask.json.provider import DefaultJSONProvider.
Expected: No ImportError on startup.
- Hit your JSON endpoints and confirm the output matches the old format.
Expected: Responses are byte-identical to before the upgrade.
When to use this
Use when a Flask 2.2/2.3 upgrade breaks a custom JSON encoder imported from flask.json.
When NOT to use this
Not for 'Object of type X is not JSON serializable' at runtime; that means the provider is fine but a type lacks a handler.
Version notes
JSONEncoder deprecated in Flask 2.2, removed in 2.3. DefaultJSONProvider is the replacement across 2.2+ and 3.x.
Why it happens
Flask replaced its encoder-class customization point with a provider class. The old JSONEncoder name was deleted, so any subclass import fails immediately on Flask 2.3+.
Edge cases
app.json_encoder assignments are also ignored on 2.2+; the provider class is the only hook that still works.
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.