[Fixed] Flask AttributeError: module 'flask.json' has no attribute 'JSONEncoder' – Flask

by
Ali Hasan
flask llama-cpp-python

Quick Fix: Remove JSONEncoder = json.JSONEncoder and add from json import JSONEncoder as Flask’s version is redundant. Update flask-wtf library if it’s causing the issue.

The Problem:

After upgrading Flask and its dependencies, a Flask application encounters an AttributeError: module ‘flask.json’ has no attribute ‘JSONEncoder’. This error occurs when attempting to import the JSONEncoder class from the flask.json module, which is used for encoding data in JSON format. The issue arises due to changes in the Flask framework or its dependencies, resulting in the removal or relocation of the JSONEncoder class.

The Solutions:

Solution 1: Import JSONEncoder from json module

Since Python 3.2, JSONEncoder is a built-in part of Python, making Flask’s version redundant. To fix the issue, replace the line that imports JSONEncoder from Flask’s json module with:

from json import JSONEncoder

Solution 2: Downgrading Flask Version

This solution suggests downgrading the installed Flask version to an older one. Use the following commands:

pip uninstall Flask
pip install Flask==2.2.3

However, this solution might not fully resolve the issue, as the user continued to encounter errors after downgrading.

Solution 3: Install older version of flask

To fix this issue, you can install an older version of Flask that still has the JSONEncoder attribute. For example, you can install Flask version 2.2.2 using the following command:


pip install Flask==2.2.2

Solution 4: Upgrade Flask-WTF package

The error suggests that the JSONEncoder attribute is missing from the flask.json module. This is likely due to an incompatibility between the current version of Flask-WTF and the upgraded version of Flask. To resolve this, upgrade Flask-WTF to the latest version:

pip install Flask-WTF~=1.1.1

Solution 5: Update Connexion version

The error is caused by a change in the way Flask manages its dependencies. In previous versions of Flask, the JSONEncoder class was located in the flask.json module. However, in the current version of Flask, the JSONEncoder class has been moved to the json module. To fix the error, you can either update your version of connexion to a version that is compatible with the current version of Flask, or you can manually import the JSONEncoder class from the json module.

Video Explanation:

The following video, titled "module 'collections' has no attribute 'Iterator' | Django | Python ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Attribute Error : module 'collections' has no attribute 'Iterator' | Django | Python | Flask Error · Comments8.