json相关obj序列化库及使用

来源:互联网 发布:淘宝steam慈善包送大作 编辑:程序博客网 时间:2024/05/20 21:45

一 obj->dict->json

1 datetime.datetime 针对datetime 

把dict中的datetime元素转成string,从而实现dict->json

def default(obj):    """Default JSON serializer."""    if isinstance(obj, datetime.datetime):        if obj.utcoffset() is not None:            obj = obj - obj.utcoffset()    millis = int(        calendar.timegm(obj.timetuple()) * 1000 +        obj.microsecond / 1000    )    return millisjson.dumps(obj,default=default)

2 普通 encoder 把obj转成dict
def default(obj):    """Default JSON serializer."""    if isinstance(obj, datetime.datetime):        if obj.utcoffset() is not None:            obj = obj - obj.utcoffset()    millis = int(        calendar.timegm(obj.timetuple()) * 1000 +        obj.microsecond / 1000    )    return millis

3 使用第三方库
from bson.json_util import dumps as json_dumpsjson_dumps(obj...)

二  json->dict->str

1 自己写解码器
class MyDecoder(json.JSONDecoder):      def __init__(self):          json.JSONDecoder.__init__(self, object_hook=self.dict_to_object)      def dict_to_object(self, d):          if '__class__' in d:              class_name = d.pop('__class__')              module_name = d.pop('__module__')              module = __import__(module_name)              print 'MODULE:', module              class_ = getattr(module, class_name)              print 'CLASS:', class_              args = dict( (key.encode('ascii'), value) for key, value in d.items())              print 'INSTANCE ARGS:', args              inst = class_(**args)          else:              inst = d          return inst  

2 使用第三方库
from bson.json_util import loads as json_loadsjson_loads(obj...)


JAVASCRIPT json使用:

How to parse JSON in JavaScript   

Serializing to JSON in jQuery

0 0
原创粉丝点击