How to fix AttributeError module ‘json’ has no attribute ‘dumps’ in Python

AttributeError module 'json' has no attribute 'dumps'

AttributeError module ‘json’ has no attribute ‘dumps’ is an error that occurs when in the same path we have a file named “json.py”. It is very simple to fix this. We need to rename the file ” json.py” to a different name.

What causes the AttributeError module ‘json’ has no attribute ‘dumps’ in Python?

This error occurs when we have a file named “json.py” local because this file name matches the name of the json module, so when running the program, Python has loaded this “json.py” file, which this file has no ‘dumps’ attribute. Or by importing another module with the same alias.

The first reason, you have a file named “json.py”
Because this file has the same name as the module, an error occurs.

Example:

import json
json.dumps([])

Output:

AttributeError 'module' object has no attribute 'dumps'

The second reason is that the same alias
You import the json module, then import another module with the same alias.

Example:

import json

# Use an alias with same name as json module
import datetime as json

json.dumps([])

Output:

AttributeError: module 'datetime' has no attribute 'dumps'

Solution for the AttributeError module ‘json’ has no attribute ‘dumps’

Fixing this error is very simple. We need to rename the file “json.py” to a different name to avoid matching the name of the json module and use a different alias.

Rename the file “json.py”

This file has the same name as the json module. We must give it a different name. For example, change “json.py” to “json2.py”. Then rerun the code to see the difference.

Example:

import json

student = json.dumps({'name': 'John', 'age': 20})
print(student)

Output:

{"name": "John", "age": 20}

Rename Alias

Choose a different alias name that does not match the name of the json module.

Example:

import json

# Choose "dateTimeAlias" name instead of "json"
import datetime as dateTimeAlias

json.dumps([])

You can print out the attributes of the module you import using the “dir()” function to see what attributes the module has.

Example:

import json

# Use "dir()" to print out the attributes of the module
print(dir(json))

Output:

['JSONDecodeError', 'JSONDecoder', 'JSONEncoder', 'all', 'author', 'builtins', 'cached', 'file', 'loader', 'name', 'package', 'path', 'spec', 'version', '_default_decoder', '_default_encoder', 'codecs', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner']

There is a similar post about this error.

Summary

Through the article, we have found the cause of the AttributeError module ‘json’ has no attribute ‘dumps’. The way to avoid this error is effortless. We need to make sure there is no file named “json.py”. Hope you get it fixed soon.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *