Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'str' object has no attribute '__dict__'

I want to serialize a dictionary to JSON in Python. I have this 'str' object has no attribute 'dict' error. Here is my code...

from django.utils import simplejson

class Person(object):
    a = ""

person1 = Person()
person1.a = "111"

person2 = Person()
person2.a = "222"

list = {}
list["first"] = person1
list["second"] = person2

s = simplejson.dumps([p.__dict__ for p in list])

And the exception is;

Traceback (most recent call last):
  File "/base/data/home/apps/py-ide-online/2.352580383594527534/shell.py", line 380, in post
    exec(compiled_code, globals())
  File "<string>", line 17, in <module>
AttributeError: 'str' object has no attribute '__dict__'
like image 208
syloc Avatar asked Sep 21 '11 10:09

syloc


3 Answers

How about

s = simplejson.dumps([p.__dict__ for p in list.itervalues()])
like image 170
NPE Avatar answered Nov 05 '22 16:11

NPE


What do you think [p.__dict__ for p in list] does?

Since list is not a list, it's a dictionary, the for p in list iterates over the key values of the dictionary. The keys are strings.

Never use names like list or dict for variables.

And never lie about a data type. Your list variable is a dictionary. Call it "person_dict` and you'll be happier.

like image 24
S.Lott Avatar answered Nov 05 '22 17:11

S.Lott


You are using a dictionary, not a list as your list, in order your code to work you should change it to a list e.g.

list = []
list.append(person1)
list.append(person2)
like image 3
Kimvais Avatar answered Nov 05 '22 16:11

Kimvais