一 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 millis
json.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_dumps
json_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_loads
json_loads(obj...)
JAVASCRIPT json使用:
How to parse JSON in JavaScript
Serializing to JSON in jQuery
最后
以上就是勤奋星月最近收集整理的关于json相关obj序列化库及使用 Serializing to JSON in jQuery的全部内容,更多相关json相关obj序列化库及使用内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复