Python Language Data Serialization

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Python Language Question?