Python pickle serialize and deserialize an object. For example, you can serialize an object into a file
and save it on you hard disk or pass it over the internet, and next time when you need it, deserialize the file.
pickle has two methods, load and dump. load deserialize, and
dump serialize respectively.
Suppose we have a json file "tp.json":
{
"Mike": {
"name": "Mike Johnson",
"age": 32
}
"Jeff": {
"name": "Jeffrey Smith",
"age": 27
}
"Lynn": {
"Lynn Martin",
"age": 54
}
}
Following Python code convert the json into dictionary and then save it to file "tp.txt":
>>> import json
>>> import pickle
>>> fl = open('tp.json').read()
>>> jn = json.loads(fl)
>>> pickle.dump(jn,open("tp.txt","w"))
The file can be loaded and deserialed into a dictionary and print out:
>>> jn = pickle.load(open("tp.txt","r"))
... for key in jn:
... print(key)
... for key2 in jn[key]:
... print(key2, ": ", jn[key][key2])
...
Lynn name : Lynn Martin age : 54 Jeff name : Jeffrey Smith age : 27 Mike name : Mike Johnson age : 32