-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython-json.py
More file actions
92 lines (78 loc) · 2.59 KB
/
Copy pathpython-json.py
File metadata and controls
92 lines (78 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#定义一个类person
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)
if __name__ == '__main__':
p=Person('Peter',22)
print p
#如果直接通过json.dumps方法对Person的实例进行处理的话,会报错,因为json无法支持这样的自动转化。通过上面所提到的json和python的类型转化对照表,可以发现,object类型是和dict相关联的,所以我们需要把我们自定义的类型转化为dict,然后再进行处理。这里,有两种方法可以使用。
#新文件
#方法1:继承JSONEncoder和JSONDecoder类,覆写相关方法
import Person
import json
p=Person.Person('Peter',22)
class MyEncoder(json,JSONEncoder):
def default(self,obj)
#convert object to a dict
d={}
d['__class__']=obj.__class__.__name__
d['__module__']=obj.__module__
d.updata(obj.__dict__)
return d
class MyDecoder(json.JSONDecoder):
def __init__(self):
json.JSONDecoder.__init__(self,object_hook=self.dic2object)
def dict2object(self,d):
#convert dict to object
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
inst=class_(**args) #create new instance
else:
inst = d
return inst
d = MyEncoder().encode(p)
o = MyDecoder().decode(d)
print d
print type(o),o
#方法2:自己写转化函数
import Person
import json
p=Person.Person('Peter',22)
def object2dict(obj):
#convert object to a dict
d={}
d['__class__']=obj.__class__.__name__
d['__module__']=obj.__module__
d.update(obj.__dict__)
return d
def dict2object(d):
#convert dict to object
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
inst=class_(**args) #create new instance
else:
inst=d
return inst
d=object2dict(p)
print d
#{'age':22,'__module__':'Person','__class__':'Person','name':'Peter'}
o=dict2object(d)
print type(o),o
#<class 'Person.Person'> Person Object name : Peter, age:22
dump=json.dumps(p,default=object2dict)
print dump
#{"age":22,"__module__":"Person","__class__":"Person","name":"Peter"}
load=json.loads(dump,object_hook=dict2object)
print load
#Person Object name : Peter,age:22