|
本帖最后由 alison 于 2019-2-22 21:54 编辑
练习json module的时候,出现keywords must be strings 错误,求大神指点一二!
- import json
- class Person(object):
- def __init__(self, name, age):
- self.name = name
- self.age = age
- def __repr__(self):
- return 'Person Object name : %s , age : %d' % (self.name, self.age)
- def object2dict(obj):
- '''
- convert Person to dict
- '''
- d = {}
- d['__class__'] = obj.__class__.__name__
- d['__module__'] = obj.__module__
- d.update(obj.__dict__)
- return d
- def dict2object(d):
- '''
- convert dict ot Person
- '''
- if '__class__' in d:
- class_name = d.pop('__class__')
- module_name = d.pop('__module__')
- module = __import__(module_name)
- class_ = getattr(module, class_name)
- args = dict((key.encode('ascii'), value) for key, value in d.items()) # get args
- print(args)
- inst = class_(**args) # create new instance
- else:
- inst = d
- return inst
- if __name__ == '__main__':
- p = Person('alison', 40)
- print(p)
- d = object2dict(p)
- print(d)
- o = dict2object(d)
- print(type(o), o)
- dump = json.dumps(p, default=object2dict)
- print(dump)
- load = json.loads(dump, object_hook=dict2object)
- print(load)
复制代码
报错:
Traceback (most recent call last):
{'__class__': 'Person', '__module__': '__main__', 'name': 'alison', 'age': 40}
{b'name': 'alison', b'age': 40}
File "G:/workspace/PycharmProjects/module/jsonDemo.py", line 52, in <module>
o = dict2object(d)
File "G:/workspace/PycharmProjects/module/jsonDemo.py", line 41, in dict2object
inst = class_(**args) # create new instance
TypeError: __init__() keywords must be strings
|
|