Python類轉json

import json
import codecs

def utf16_le_to_utf_8(data):
    decode = codecs.getdecoder('utf_16_le')
    rv = decode(data)[0]
    return rv

def _to_json_obj(src, anchor=None):

    def _judge_anchor(_item, _src, _anchor):
        __anchor = _anchor if isinstance(_src, (tuple, list, dict)) else _src
        _valid_item = True if not isinstance(_anchor, type(_item)) else False
        return _valid_item, __anchor

    def _build_in_to_json_obj(_src):
        if isinstance(_src, bytes):
            _dst = utf16_le_to_utf_8(_src)
        else:
            _dst = _src
        return _dst

    def _list_to_json_obj(_src, _anchor=None):
        _dst = []
        for i in range(0, len(_src)):
            _dst.append(_to_json_obj(_src[i], anchor=_anchor))
        return _dst

    def _dict_to_json_obj(_src, _anchor=None):
        _dst = dict()
        for k, v in _src.items():
            _dst[k] = _to_json_obj(v, anchor=_anchor)
        return _dst

    def _class_to_json_obj(_src, _anchor=None):
        _dst = dict()
        for k, v in _src.__dict__.items():
            valid_item, __anchor = _judge_anchor(v, _src, _anchor)
            if valid_item:
                _dst[k] = _to_json_obj(v, anchor=__anchor)
        return _dst

    if isinstance(src, (type(None), bool, int, float, str, bytes)):
        dst = _build_in_to_json_obj(src)
    elif isinstance(src, (list, tuple)):
            dst = _list_to_json_obj(src, _anchor=anchor)
    elif isinstance(src, dict):
            dst = _dict_to_json_obj(src, _anchor=anchor)
    else:
            dst = _class_to_json_obj(src, _anchor=anchor)
    return dst


def to_json_str(anything):
    obj = _to_json_obj(anything)
    return json.dumps(obj, indent=4, ensure_ascii=False)
相關文章
相關標籤/搜索