syloc
syloc

Reputation: 4709

'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__'

Upvotes: 10

Views: 23644

Answers (3)

S.Lott
S.Lott

Reputation: 391848

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.

Upvotes: 6

Kimvais
Kimvais

Reputation: 39548

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)

Upvotes: 3

NPE
NPE

Reputation: 500297

How about

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

Upvotes: 7

Related Questions