.


:




:

































 

 

 

 


json




pickle json load(), , json Python, json .

>>> shell
2
>>> del entry ①
>>> entry
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'entry' is not defined
>>> import json
>>> with open('entry.json', 'r', encoding='utf-8') as f:
... entry = json.load(f) ②
...
>>> entry ③
{'comments_link': None,
'internal_id': {'__class__': 'bytes', '__value__': [222, 213, 180, 248]},
'title': 'Dive into history, 2009 edition',
'tags': ['diveintopython', 'docbook', 'html'],
'article_link': 'http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition',
'published_date': {'__class__': 'time.asctime', '__value__': 'Fri Mar 27 22:20:42 2009'},
'published': True}

① Python entry Pickle.

② json.load() pickle.load(). , Python.

③ . , json.load() entry.json, Python Python, . : entry. 'internal_id' 'published_date' - , json ( to_json())

json.load() , json.dump(). , to_json() , json Python.

# add this to customserializer.py
def from_json(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

① . - , Python - JSON, Python.

② , , '__class__', to_json(). , , , Python

③ time.asctime() time.strptime(). ( , time.asctime()) time.struct_time

④ bytes bytes()

, to_json() from_json(). :

>>> shell
2
>>> import customserializer
>>> with open('entry.json', 'r', encoding='utf-8') as f:
... entry = json.load(f, object_hook=customserializer.from_json) ①
...
>>> entry ②
{'comments_link': None,
'internal_id': b'\xDE\xD5\xB4\xF8',
'title': 'Dive into history, 2009 edition',
'tags': ['diveintopython', 'docbook', 'html'],
'article_link': 'http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition',
'published_date': time.struct_time(tm_year=2009, tm_mon=3, tm_mday=27, tm_hour=22, tm_min=20, tm_sec=42, tm_wday=4, tm_yday=86, tm_isdst=-1),
'published': True}

① from_json() , object_hook json.load(). , !

② entry 'internal_id' bytes. 'published_date' time.struct_time.

.

>>> shell
1
>>> import customserializer
>>> with open('entry.json', 'r', encoding='utf-8') as f:
... entry2 = json.load(f, object_hook=customserializer.from_json)
...
>>> entry2 == entry ①
False
>>> entry['tags'] ②
('diveintopython', 'docbook', 'html')
>>> entry2['tags'] ③
['diveintopython', 'docbook', 'html']

① to_json() from_json() . ?

② entry 'tags' .

③ entry2 'tags' - . JSON , , , json - json . , , , json.





:


: 2016-11-18; !; : 555 |


:

:

. .
==> ...

1464 - | 1426 -


© 2015-2024 lektsii.org - -

: 0.007 .