I am running Python 2.7 (x64 Linux) and trying to convert a dict
to a JSON object.
>>> import sys
>>> sys.version_info
sys.ver
Turned out I had an old json
library loaded from an old Python installation:
>>> import json
>>> print json.__file__
/home/areynolds/opt/lib/python2.5/site-packages/json.pyc
Removing that old stuff fixed the issue. Thanks!
You may have another script in your Python path called "json", which you are importing by accident. You could resolve this either by renaming the one under your control or using
from __future__ import absolute_import
I create a file named json.py. When I run this I got the error, so I rename it and it words for me.
AttributeError: 'module' object has no attribute 'dumps'
You probably created a file called json.py that was reachable from python's sys.path
. Or you added a directory to your python's sys.path that included a file called json.py.
Option 1: Poison the well by importing json, then importing another module with the same alias:
eric@dev /var/www/sandbox/eric $ python
>>> import json
>>> json.dumps([])
'[]'
>>> import sys as json
>>> json.dumps([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'dumps'
Option 2: Poison the well by creating a file called json.py in the python path:
Create a new file json.py, save it. Put this code in there:
def foo():
print "bar"
Open the python terminal and import json:
eric@dev /var/www/sandbox/eric/wsgi $ python
>>> import json
>>> type(json)
<type 'module'>
>>> json.dumps([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'dumps'
>>> json.foo()
bar
It's telling you your method isn't there. So ask python to tell you more about the nature of this module and you'll find clues as to who poisoned it.
>>> print json
<module 'json' from 'json.py'>
>>> dir(json)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'foo']
>>> type(json)
<type 'module'>
This error just occurred for me in a different context, but still one of two things named json. I had named a "view" in Django (a Python function that prepares a response to an HTTP request), in this case a view to handle request for data in json format.
But I had named the view "json". Bad move. I was mystified when print dir(json) returned a dumps-free response in my view "json" whereas it showed "dumps" as an attribute in a similar view that worked.
This discussion fixed the problem for me.
Had a similar issues, it was caused by another custom module. I named another script
json.py
and it turns out it tried to load the custom json.py file as a module. dumps method is obviously not available there.
Renaming the json.py script to something else (json2.py) got rid of the issue.