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__'
How about
s = simplejson.dumps([p.__dict__ for p in list.itervalues()])
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.
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)
精彩评论