mirror of
https://github.com/kennethreitz/dive-into-python3.git
synced 2026-06-05 23:10:17 +00:00
example code for serializing chapter
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import pickle
|
||||
import json
|
||||
import time
|
||||
|
||||
def custom_encoder(python_object):
|
||||
if isinstance(python_object, time.struct_time):
|
||||
return {'__class__': 'time.asctime',
|
||||
'__value__': time.asctime(python_object)}
|
||||
if isinstance(python_object, bytes):
|
||||
return {'__class__': 'bytes',
|
||||
'__value__': list(python_object)}
|
||||
raise TypeError(repr(python_object) + ' is not JSON serializable')
|
||||
|
||||
def custom_decoder(json_object):
|
||||
if '__class__' in json_object:
|
||||
if json_object['__class__'] == 'time.asctime':
|
||||
return time.strptime(json_object['__value__'])
|
||||
if json_object['__class__'] == 'bytes':
|
||||
return bytes(json_object['__value__'])
|
||||
return json_object
|
||||
|
||||
if __name__ == '__main__':
|
||||
entry = {}
|
||||
entry['title'] = 'Dive into history, 2009 edition'
|
||||
entry['article_link'] = 'http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition'
|
||||
entry['comments_link'] = None
|
||||
entry['internal_id'] = b'\xde\xd5\xb4\xf8'
|
||||
entry['tags'] = ('diveintopython', 'docbook', 'html')
|
||||
entry['published'] = True
|
||||
entry['published_date'] = time.strptime('Fri Mar 27 22:20:42 2009')
|
||||
|
||||
with open('entry.pickle', 'wb') as f:
|
||||
pickle.dump(entry, f)
|
||||
|
||||
with open('entry.pickle', 'rb') as f:
|
||||
entry2 = pickle.load(f)
|
||||
|
||||
print(entry == entry2)
|
||||
print(type(entry['tags']))
|
||||
print(type(entry2['tags']))
|
||||
|
||||
with open('entry.json', 'w', encoding = 'utf-8') as f:
|
||||
json.dump(entry, f, default = custom_encoder)
|
||||
|
||||
with open('entry.json', 'r', encoding = 'utf-8') as f:
|
||||
entry2 = json.load(f, object_hook = custom_decoder)
|
||||
|
||||
print(entry == entry2)
|
||||
print(type(entry['tags']))
|
||||
print(type(entry2['tags']))
|
||||
Reference in New Issue
Block a user