python提供了json包來進行json處理,json與python中數據類型對應關系如下:
一個python object無法直接與json轉化,只能先將對象轉化成dictionary,再轉化成json;對json,也只能先轉換成dictionary,再轉化成object,通過實踐,源碼如下:
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
|
import json class user: def __init__( self , name, pwd): self .name = name self .pwd = pwd def __str__( self ): return 'user(' + self .name + ',' + self .pwd + ')' #重寫JSONEncoder的default方法,object轉換成dict class userEncoder(json.JSONEncoder): def default( self , o): if isinstance (o, user): return { 'name' : o.name, 'pwd' : o.pwd } return json.JSONEncoder.default(o) #重寫JSONDecoder的decode方法,dict轉換成object class userDecode(json.JSONDecoder): def decode( self , s): dic = super ().decode(s) return user(dic[ 'name' ], dic[ 'pwd' ]) #重寫JSONDecoder的__init__方法,dict轉換成object class userDecode2(json.JSONDecoder): def __init__( self ): json.JSONDecoder.__init__( self , object_hook = dic2objhook) # 對象轉換成dict def obj2dict(obj): if ( isinstance (obj, user)): return { 'name' : obj.name, 'pwd' : obj.pwd } else : return obj # dict轉換為對象 def dic2objhook(dic): if isinstance (dic, dict ): return user(dic[ 'name' ], dic[ 'pwd' ]) return dic # 第一種方式,直接把對象先轉換成dict u = user( 'smith' , '123456' ) uobj = json.dumps(obj2dict(u)) print ( 'uobj: ' , uobj) #第二種方式,利用json.dumps的關鍵字參數default u = user( 'smith' , '123456' ) uobj2 = json.dumps(u, default = obj2dict) print ( 'uobj2: ' , uobj) #第三種方式,定義json的encode和decode子類,使用json.dumps的cls默認參數 user_encode_str = json.dumps(u, cls = userEncoder) print ( 'user2json: ' , user_encode_str) #json轉換為object u2 = json.loads(user_encode_str, cls = userDecode) print ( 'json2user: ' , u2) #另一種json轉換成object的方式 u3 = json.loads(user_encode_str, cls = userDecode2) print ( 'json2user2: ' , u3) |
輸出結果如下:
1
2
3
4
5
6
7
8
|
C:\python\python.exe C: / Users / Administrator / PycharmProjects / pytest / com / guo / myjson.py uobj: { "name" : "smith" , "pwd" : "123456" } uobj2: { "name" : "smith" , "pwd" : "123456" } user2json: { "name" : "smith" , "pwd" : "123456" } json2user: user(smith, 123456 ) json2user2: user(smith, 123456 ) Process finished with exit code 0 |
以上這篇對python中Json與object轉化的方法詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/wlsyn/article/details/52150217