Pickle序列化
python的pickle模块实现了基本的数据序列和反序列化。通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储;通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象
JSON(JavaScript Object Notation)
json是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。marshal
marshal并不是一个通用的模块,在某些时候它是一个不被推荐使用的模块,因为使用marshal序列化的二进制数据格式还没有文档化,在不同版本的Python中,marshal的实现可能不一样。也就是说,用python2.5序列为一个对象,用python2.6的程序反序列化所得到的对象,可能与原来的对象是不一样的。但这个模块存在的意义,正如Python手册中所说:The marshal module exists mainly to support reading and writing the “pseudo-compiled” code for Python modules of .pyc files.代码示例
#!/usr/bin/python
# encoding:utf-8
import pickle
import marshal
import json
#创建一个对象
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def sayHi(self):
print 'Hello, my name is', self.name
#继承JSONEncoder和JSONDecoder类,覆写相关方法,实现自定义对象的JSON
class MyEncoder(json.JSONEncoder):
def default(self, obj):
# convert object to a dict
d = {}
d['__class__'] = obj.__class__.__name__
d['__module__'] = obj.__module__
d.update(obj.__dict__)
return d
class MyDecoder(json.JSONDecoder):
def __init__(self):
json.JSONDecoder.__init__(self, object_hook=self.dict2object)
def dict2object(self, d):
# convert dict to object
if '__class__' in d:
class_name = d.pop('__class__')
module_name = d.pop('__module__')
module = __import__(module_name)
class_ = getattr(module, class_name)
args = dict((key.encode('ascii'), value) for key, value in d.items()) # get args
inst = class_(**args) # create new instance
else:
inst = d
return inst
P = {'B': -0.26268660809250016,
'E': -3.14e+100,
'M': -3.14e+100,
'S': -1.4652633398537678}
def testPickle():
p1 = Person("Tom", 10)
p1.sayHi()
outFile = open("p.p", 'wb')
pickle.dump(p1, outFile, 1);
outFile.close()
inFile = open("p.p", 'rb')
p2 = pickle.load(inFile)
inFile.close()
p2.sayHi()
def testMarshal():
outFile = open("p.p", 'wb')
marshal.dump(P, outFile);
outFile.close()
start_p = {}
with open('p.p', 'rb') as f:
start_p = P
for a in start_p:
print(start_p[a])
#测试处理普通的python内置类型
def testJson():
obj = [[1, 2, 3], 123, 123.123, 'abc', {'key1': (1, 2, 3), 'key2': (4, 5, 6)}]
encodedjson = json.dumps(obj)
print repr(obj)
print encodedjson
decodejson = json.loads(encodedjson)
print type(decodejson)
print decodejson[4]['key1']
print decodejson
#测试处理自定义类型
def testJsonObj():
p = Person("Tom", 10)
d = MyEncoder().encode(p)
o = MyDecoder().decode(d)
print d
print type(o), o
o.sayHi()
if __name__ == '__main__':
testPickle()
print("================================")
testMarshal()
print("================================")
testJson()
print("================================")
testJsonObj()
print("================================")
参考
http://blog.csdn.net/mldxs/article/details/8574518
http://www.cnblogs.com/coser/archive/2011/12/14/2287739.html