'str'对象没有属性'__dict__'

syl*_*loc 7 python serialization json dictionary

我想在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])
Run Code Online (Sandbox Code Playgroud)

例外是;

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__'
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 7

怎么样

s = simplejson.dumps([p.__dict__ for p in list.itervalues()])
Run Code Online (Sandbox Code Playgroud)


S.L*_*ott 5

你觉得有什么[p.__dict__ for p in list]作用?

由于list不是列表,而是字典,因此for p in list迭代字典的键值。键是字符串。

永远不要使用变量名listdict变量名。

永远不要在数据类型上撒谎。你的list变量是一本字典。称之为“person_dict”,你会更快乐。