您的位置:首页 > 编程语言 > Python开发

PyCon 2011 - Hidden Treasures of the Python Standard Library - json序列化操作

2011-03-30 00:19 681 查看


本作品采用知识共享署名-非商业性使用-相同方式共享 3.0 Unported许可协议进行许可。允许非商业转载,但应注明作者及出处。

作者:liuyuan_jq

2011-03-30

json简介

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。
它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition -
December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#,
Java, JavaScript, Perl, Python等)。 这些特性使JSON成为理想的数据交换语言。

json资源

http://www.json.org/json-zh.html

http://woodpecker.org.cn/diveintopython3/serializing.html

simplejson

如果你使用的是python2.6以下的版本,需要手动安装simplejson支持json

easy_install simplejson

自定义序列化对象

#!/usr/bin/env python
# encoding: utf-8
# json_myobj.py
""" Define a class to be encoded.
"""
class MyObj(object):
def __init__(self, s):
self.s = s
def __repr__(self):
return '<MyObj(%s)>' % self.s


dumps操作

#!/usr/bin/env python
# encoding: utf-8
# json_dump_default.py
"""Serialize a custom object to JSON.
"""
import hmac
import json_myobj
try:
import json
except:
import simplejson as json
"""
# python json_dump_default.py
{
"s"            : "instance value goes here",
"__module__"   : "json_myobj",
"__signature__": "426f662f9fe3b3533d9ce7f9dcf8af77",
"__class__"    : "MyObj"
}
"""
def convert_to_builtin_type(obj):
"""object->dictionary"""
print 'convert_to_builtin_type(%r)' % obj
# convert_to_builtin_type(<MyObj(instance value goes here)>)
class_name = obj.__class__.__name__
module_name = obj.__module__
digest_maker = hmac.new('PyCon2011',              # 公钥
module_name + class_name) # 发送的信息
signature = digest_maker.hexdigest() # 生成摘要
d = { '__class__':class_name,
'__module__':module_name,
'__signature__':signature,
}
d.update(obj.__dict__)
return d
obj = json_myobj.MyObj('instance value goes here')
print json.dumps(obj, default=convert_to_builtin_type)


loads操作

#!/usr/bin/env python
# encoding: utf-8
"""Load a custom object from JSON serlized version.
"""
import hmac
try:
import json
except:
import simplejson as json
def dict_to_object(d):
if '__class__' not in d:
return d

class_name = d.pop('__class__')
module_name = d.pop('__module__')
signature = d.pop('__signature__')
digest_maker = hmac.new('PyCon2011',
module_name + class_name)
expected_signature = digest_maker.hexdigest()
if signature != expected_signature:
raise ValueError('Invalid signature')

print 'Loading "%s" from "%s"' % /
(class_name, module_name)
module = __import__(module_name)
class_ = getattr(module, class_name)

args = dict( (key.encode('ascii'), value)
for key, value in d.items())
print 'Instantiating with', args

inst = class_(**args)
return inst
for encoded_object in [
'''
[{"s": "instance value goes here",
"__signature__": "426f662f9fe3b3533d9ce7f9dcf8af77",
"__module__": "json_myobj", "__class__": "MyObj"}]
''',

# careful!
'''
[{"path": "/etc/passwd",
"__signature__": "426f662f9fe3b3533d9ce7f9dcf8af77",
"__module__": "os", "__class__": "unlink"}]
''',
]:
try:
myobj_instance = json.loads(
encoded_object,
object_hook=dict_to_object,
)
print myobj_instance
except Exception, err:
print 'ERROR:', err
print
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐