Data Serialization

Download python eBook

Syntax

  • unpickled_string = pickle.loads(string)
  • unpickled_string = pickle.load(file_object)
  • pickled_string = pickle.dumps([('', 'cmplx'), {('object',): None}], pickle.HIGHEST_PROTOCOL)
  • pickle.dump(('', 'cmplx'), {('object',): None}], file_object, pickle.HIGHEST_PROTOCOL)
  • unjsoned_string = json.loads(string)
  • unjsoned_string = json.load(file_object)
  • jsoned_string = json.dumps(('a', 'b', 'c', [1, 2, 3]))
  • json.dump(('a', 'b', 'c', [1, 2, 3]), file_object)

Parameters

ParameterDetails
protocolUsing pickle or cPickle, it is the method that objects are being Serialized/Unserialized. You probably want to use pickle.HIGHEST_PROTOCOL here, which means the newest method.

Remarks

Why using JSON?

  • Cross language support
  • Human readable
  • Unlike pickle, it doesn't have the danger of running arbitrary code

Why not using JSON?

  • Doesn't support Pythonic data types
  • Keys in dictionaries must not be other than string data types.

Why Pickle?

  • Great way for serializing Pythonic (tuples, functions, classes)
  • Keys in dictionaries can be of any data type.

Why not Pickle?

  • Cross language support is missing
  • It is not safe for loading arbitrary data

Related Examples

Stats

79 Contributors: 3
Wednesday, August 3, 2016
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook