ext.py 文件源码

python
阅读 40 收藏 0 点赞 0 评论 0

项目:LineBot 作者: RaenonX 项目源码 文件源码
def object_to_json(o, level=0, indent=4, space=" ", newline="\n"):
    ret = ""
    if isinstance(o, dict):
        ret += "{" + newline
        comma = ""
        for k,v in o.iteritems():
            ret += comma
            comma = ",\n"
            ret += space * indent * level
            ret += '"' + str(k) + '":' + space
            ret += object_to_json(v, level + 1)

        ret += newline + space * indent * (level - 1) + "}"
    elif isinstance(o, basestring):
        ret += '"' + o + '"'
    elif isinstance(o, list):
        ret += "[" + ", ".join([object_to_json(e, level+1) for e in o]) + "]"
    elif isinstance(o, bool):
        ret += "true" if o else "false"
    elif isinstance(o, (int, long)):
        ret += str(o)
    elif isinstance(o, datetime):
        ret += o.strftime('%Y-%m-%d %H:%M:%S.%f')
    elif isinstance(o, bson.ObjectId):
        ret += 'ObjectId(%s)' % o
    elif isinstance(o, float):
        ret += '%.7g' % o
    elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.integer):
        ret += "[" + ','.join(map(str, o.flatten().tolist())) + "]"
    elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.inexact):
        ret += "[" + ','.join(map(lambda x: '%.7g' % x, o.flatten().tolist())) + "]"
    elif isinstance(o, bson.timestamp.Timestamp):
        ret += o.as_datetime().strftime('%Y-%m-%d %H:%M:%S.%f')
    elif o is None:
        ret += 'null'
    else:
        raise TypeError("Unknown type '%s' for json serialization" % str(type(o)))
    return ret
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号