Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize Python objects in a human-readable format? [closed]

I need to store Python structures made of lists / dictionaries, tuples into a human-readable format. The idea is like using something similar to pickle, but pickle is not human-friendly. Other options that come to my mind are YAML (through PyYAML and JSON (through simplejson) serializers.

Any other option that comes to your mind?

like image 542
pistacchio Avatar asked Jan 03 '09 10:01

pistacchio


People also ask

How do you serialize in Python?

Pickle. Pickling is the process whereby a Python object hierarchy is converted into a byte stream (usually not human readable) to be written to a file, this is also known as Serialization. Unpickling is the reverse operation, whereby a byte stream is converted back into a working Python object hierarchy.

Is Pickle human readable?

The Python pickle module is another way to serialize and deserialize objects in Python. It differs from the json module in that it serializes objects in a binary format, which means the result is not human readable.

What is serializing and Deserializing in Python?

Object serialization is the process of converting state of an object into byte stream. This byte stream can further be stored in any file-like object such as a disk file or memory stream. It can also be transmitted via sockets etc. Deserialization is the process of reconstructing the object from the byte stream.


1 Answers

For simple cases pprint() and eval() come to mind.

Using your example:

>>> d = {'age': 27, ...  'name': 'Joe', ...  'numbers': [1,  ...              2,  ...              3, ...              4, ...              5], ...  'subdict': { ...              'first': 1,  ...              'second': 2, ...               'third': 3 ...              } ... } >>>  >>> from pprint import pprint >>> pprint(d) {'age': 27,  'name': 'Joe',  'numbers': [1, 2, 3, 4, 5],  'subdict': {'first': 1, 'second': 2, 'third': 3}} >>>  

I would think twice about fixing two requirements with the same tool. Have you considered using pickle for the serializing and then pprint() (or a more fancy object viewer) for humans looking at the objects?

like image 172
PEZ Avatar answered Oct 02 '22 12:10

PEZ