JSON 字典转对象

网上搜了一圈,似乎没有字典转对象的相关内容这个东西。但能通过重载 getattr来重载获取属性的方法。利用这个思路,我编写了一个转换类能将字典转换为对象。


#coding=utf-8
'''
Created on 2016-5-8

@author: 杨同峰
'''
import time

class DictObj(object):
    def __init__(self,map):
        self.map = map

    def __setattr__(self, name, value):
        if name == 'map':
             object.__setattr__(self, name, value)
             return;
        print 'set attr called ',name,value
        self.map[name] = value

    def __getattr__(self,name):
        v = self.map[name]
        if isinstance(v,(dict)):
            return DictObj(v)
        if isinstance(v, (list)):
            r = []
            for i in v:
                r.append(DictObj(i))
            return r                      
        else:
            return self.map[name];

    def __getitem__(self,name):
        return self.map[name]

if __name__ == '__main__':
    m = {'haha':{'a':55},'bb':[{'c':32,'d':45},{'c':22,'d':56}]}
    book = DictObj(m);
    print book.bb[0].c

你可能感兴趣的:(JSON 字典转对象)