【发布时间】:2011-11-21 19:42:45
【问题描述】:
我想在 Python 中将字典序列化为 JSON。我有这个 'str' 对象没有属性 'dict' 错误。这是我的代码...
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])
例外是;
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__'
【问题讨论】:
-
避免使用列表作为变量名。通过
list = {},您已经覆盖了内置的list()构造函数。
标签: python json serialization dictionary