pythonオブジェクト回転json文字列ガジェット

1175 ワード

# -*- coding:utf-8 -*-
from datetime import datetime

#           
def obj2dict(obj):
    dd = {}
    #       
    for m in dir(obj):
        if m[0] != "_" :
            value = getattr(obj, m)
            if not callable(value):
                dd[m] = complexObj2json(value)
    return dd
    
def list2json(ll):
    res_list = []
    for item in ll:
        value = complexObj2json(item)      
        res_list.append(value)  
    return res_list 
    
def dict2json(dd):
    res = {}
    for item in dd:
        res[item] = complexObj2json(dd[item])
    return res
    
# complex obj to json
#       json   (dict、list)
def complexObj2json(obj):
    # list, set, tuple
    if isinstance(obj,(list, set, tuple)):
        return list2json(obj)
    # dict
    elif isinstance(obj,dict):
        return dict2json(obj)
    #     
    # int, long, basestring, bool, float
    elif obj == None or isinstance(obj, (int, long, basestring, bool, float)):
        return obj
    elif isinstance(obj, datetime):
        return obj.strftime("%Y-%m-%d %H:%M:%S")
    #        
    else:
        return obj2dict(obj)