Python JSON module has no attribute 'dumps'

前端 未结 10 1877
攒了一身酷
攒了一身酷 2021-01-01 09:14

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         


        
10条回答
  •  余生分开走
    2021-01-01 09:29

    How to reproduce this python error:

    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 "", line 1, in 
    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)
    
    
    >>> json.dumps([])
    Traceback (most recent call last):
      File "", line 1, in 
    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
    
    >>> dir(json)
    ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'foo']
    >>> type(json)
    
    

提交回复
热议问题