-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathJson.py
More file actions
39 lines (32 loc) · 882 Bytes
/
Copy pathJson.py
File metadata and controls
39 lines (32 loc) · 882 Bytes
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
#!/usr/bin/env python
#coding=utf-8
#json反序列化成对象
import json
class Student(object):
def __init__(self,name,age,score):
self.name=name
self.age=age
self.score=score
'''def student2dict(std):
return {
'name':std.name,
'age':std.age,
'score':std.score
}'''
class Teacher(object):
def __init__(self,name,age):
self.name=name
self.age=age
s=Student('Bob',20,88)
p=Teacher('Tach',20)
print(json.dumps(s,default=lambda obj:obj.__dict__))
print(json.dumps(p,default=lambda obj:obj.__dict__))
class Target(object):
def __init__(self,name,age,score):
self.name=name
self.age=age
self.score=score
def dict2Target(d):
return Target(d['name'],d['age'],d['score'])
json_str='{"age":20,"score":88,"name":"Bob"}'
print(json.loads(json_str,object_hook=dict2Target))