Data Serialization in Python is a method which enables the users to perform a range of exciting functions. Learn more about this module here.
Parameter Details
Using or , it is the method that objects are being Serialized/Unserialized. You probably
pickle cPickle
protocol
want to use here, which means the newest method.
pickle.HIGHEST_PROTOCOL
Data Serialization in Python using JSON
JSON is a cross language, widely used method to serialize data
Supported data types : int, float, boolean, string, list and dict. See -> JSON Wiki for more
Here is an example demonstrating the basic usage of JSON:
import json
families = (['John'], ['Mark', 'David', {'name': 'Avraham'}])
Dumping it into string
json_families = json.dumps(families)
[["John"], ["Mark", "David", {"name": "Avraham"}]]
Dumping it to file
with open('families.json', 'w') as json_file:
json.dump(families, json_file)
Loading it from string
json_families = json.loads(json_families)
Loading it from file
with open('families.json', 'r') as json_file:
json_families = json.load(json_file)
See JSON-Module for detailed information about JSON.
Data Serialization in Python using Pickle
Here is an example demonstrating the basic usage of pickle:
Importing pickle try:
import cPickle as pickle # Python 2 except ImportError:
import pickle # Python 3
Creating Pythonic object:
class Family(object):
def init(self, names):
self.sons = names
def str(self):
return ' '.join(self.sons)
my_family = Family(['John', 'David'])
Dumping to string
pickle_data = pickle.dumps(my_family, pickle.HIGHEST_PROTOCOL)
Dumping to file
with open('family.p', 'w') as pickle_file:
pickle.dump(families, pickle_file, pickle.HIGHEST_PROTOCOL)
Loading from string
my_family = pickle.loads(pickle_data)
Loading from file
with open('family.p', 'r') as pickle_file:
my_family = pickle.load(pickle_file)
See Pickle for detailed information about Pickle.
WARNING: The official documentation for pickle makes it clear that there are no security guarantees. Don’t load any data you don’t trust its origin.