Python人类可读对象序列化 [英] Python human readable object serialization

查看:40
本文介绍了Python人类可读对象序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将由列表/字典、元组组成的 Python 结构存储为人类可读的格式.这个想法就像使用类似于 pickle 的东西,但 pickle 对人类不友好.我想到的其他选项是 YAML(通过 PyYAMLJSON(通过 simplejson) 序列化程序.

您想到了其他选择吗?

解决方案

对于简单的情况,会想到 pprint() 和 eval().

使用您的示例:

<预><代码>>>>d = {'年龄':27,... 'name': '乔',...数字":[1,... 2、... 3、... 4、... 5],...'subdict':{...第一":1,...第二个":2,...第三个":3... }... }>>>>>>从 pprint 导入 pprint>>>打印(d){'年龄':27,'name': '乔',数字":[1, 2, 3, 4, 5],'subdict': {'first': 1, 'second': 2, 'third': 3}}>>>

我会三思而后行,用同一个工具解决两个需求.您是否考虑过使用 pickle 进行序列化,然后使用 pprint()(或更花哨的对象查看器)让人们查看对象?

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?

解决方案

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?

这篇关于Python人类可读对象序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆