python中Json與object轉化

python提供了json包來進行json處理,json與python中數據類型對應關係如下:
這裏寫圖片描述
一個python object無法直接與json轉化,只能先將對象轉化成dictionary,再轉化成json;對json,也只能先轉換成dictionary,再轉化成object,通過實踐,源碼如下:

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)

輸出結果如下:

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章