python Python人类可读对象序列化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/408866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:02:26  来源:igfitidea点击:

Python human readable object serialization

pythonserialization

提问by pistacchio

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 PyYAMLand JSON(through simplejson) serializers.

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

Any other option that comes to your mind?

你想到的任何其他选择?

采纳答案by PEZ

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

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

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?

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

回答by JV.

If its justPython list, dictionary and tuple object. - JSONis the way to go. Its human readable, very easy to handle and language independent too.

如果它只是Python 列表、字典和元组对象。- JSON是要走的路。它具有人类可读性,非常易于处理并且与语言无关。

Caution: Tuples will be converted to lists in simplejson.

注意:元组将被转换为 simplejson 中的列表。

In [109]: simplejson.loads(simplejson.dumps({'d':(12,3,4,4,5)}))
Out[109]: {u'd': [12, 3, 4, 4, 5]}

回答by Paul Hildebrandt

You should check out jsonpickle (https://github.com/jsonpickle/jsonpickle). It will write out any python object into a json file. You can then read that file back into a python object. The nice thing is the inbetween file is very readable because it's json.

您应该查看 jsonpickle ( https://github.com/jsonpickle/jsonpickle)。它会将任何 python 对象写出到一个 json 文件中。然后,您可以将该文件读回 python 对象。好消息是中间文件非常可读,因为它是 json。

回答by Matthew Trevor

If you're after more representations than are covered by JSON, I highly recommend checking out PyON(Python Object Notation)...although I believe it's restricted to 2.6/3.0 and above, as it relies on the astmodule. It handles custom class instances and recursive data types, amongst other features, which is more than is provided by JSON.

如果您需要比 JSON 涵盖的更多表示,我强烈建议您查看PyON(Python 对象表示法)……尽管我相信它仅限于 2.6/3.0 及更高版本,因为它依赖于ast模块。它处理自定义类实例和递归数据类型,以及其他功能,这比 JSON 提供的要多。

回答by Mike McKerns

What do you mean this is not human-readable??? ;)

你的意思是这不是人类可读的???;)

>>> d = {'age': 27, 
...   'name': 'Joe',
...   'numbers': [1,2,3,4,5],
...   'subdict': {'first':1, 'second':2, 'third':3}
... }
>>> 
>>> import pickle
>>> p = pickle.dumps(d)      
>>> p
"(dp0\nS'age'\np1\nI27\nsS'subdict'\np2\n(dp3\nS'second'\np4\nI2\nsS'third'\np5\nI3\nsS'first'\np6\nI1\nssS'name'\np7\nS'Joe'\np8\nsS'numbers'\np9\n(lp10\nI1\naI2\naI3\naI4\naI5\nas."

Ok, well, maybe it just takes some practice… or you could cheat...

好吧,也许只是需要一些练习……或者你可以作弊……

>>> import pickletools 
>>> pickletools.dis(p)
    0: (    MARK
    1: d        DICT       (MARK at 0)
    2: p    PUT        0
    5: S    STRING     'age'
   12: p    PUT        1
   15: I    INT        27
   19: s    SETITEM
   20: S    STRING     'subdict'
   31: p    PUT        2
   34: (    MARK
   35: d        DICT       (MARK at 34)
   36: p    PUT        3
   39: S    STRING     'second'
   49: p    PUT        4
   52: I    INT        2
   55: s    SETITEM
   56: S    STRING     'third'
   65: p    PUT        5
   68: I    INT        3
   71: s    SETITEM
   72: S    STRING     'first'
   81: p    PUT        6
   84: I    INT        1
   87: s    SETITEM
   88: s    SETITEM
   89: S    STRING     'name'
   97: p    PUT        7
  100: S    STRING     'Joe'
  107: p    PUT        8
  110: s    SETITEM
  111: S    STRING     'numbers'
  122: p    PUT        9
  125: (    MARK
  126: l        LIST       (MARK at 125)
  127: p    PUT        10
  131: I    INT        1
  134: a    APPEND
  135: I    INT        2
  138: a    APPEND
  139: I    INT        3
  142: a    APPEND
  143: I    INT        4
  146: a    APPEND
  147: I    INT        5
  150: a    APPEND
  151: s    SETITEM
  152: .    STOP
highest protocol among opcodes = 0
>>> 

You'd still have to read the pickled object from a file, however you wouldn't need to loadit. So, if it's a "dangerous" object, you still might be able to figure that out before doing the load. If you are stuck with a pickle, it might be a good option for deciphering what you have.

您仍然需要从文件中读取腌制对象,但是您不需load要这样做。因此,如果它是一个“危险”对象,您仍然可以在执行load. 如果您坚持使用pickle,它可能是破译您拥有的内容的好选择。

回答by Soviut

To use simplejson first easy_install simplejson:

首先使用 simplejson easy_install simplejson

import simplejson
my_structure = {"name":"Joe", "age":27, "numbers":[1,2,3,4,5], "subdict":{"first":1, "second":2, "third": 3}}
json = simplejson.dumps(my_structure)

results in json being:

结果 json 是:

{"age": 27, "subdict": {"second": 2, "third": 3, "first": 1}, "name": "Joe", "numbers": [1, 2, 3, 4, 5]}

Notice that its hardly changed the format of the dictionary at all, but you should run it through this step to ensure valid JSON data.

请注意,它几乎没有改变字典的格式,但是您应该通过此步骤运行它以确保有效的 JSON 数据。

You can further pretty print the result:

您可以进一步漂亮地打印结果:

import pprint
pprint.pprint(my_structure)

results in:

结果是:

{'age': 27,
 'name': 'Joe',
 'numbers': [1, 2, 3, 4, 5],
 'subdict': {'first': 1, 'second': 2, 'third': 3}}

回答by intellimath

There is AXON(textual) format that combine the bestof JSON, XML and YAML. AXON format is quite readable and relatively compact.

AXON相结合的(文本)格式的最好的JSON,XML和YAML的。AXON 格式非常可读且相对紧凑。

The python (2.7/3.3-3.7) module pyaxonsupports load(s)/dump(s)functionality, including iterative loading/dumping. It's sufficiently fast in order to be useful.

python (2.7/3.3-3.7) 模块pyaxon支持load(s)/dump(s)功能,包括迭代loading/ dumping。它足够快才能有用。

Consider simple example:

考虑一个简单的例子:

>>> d = {
     'age': 27, 'name': 'Joe', 
     'numbers': [1, 2, 3, 4, 5], 
     'subdict': {'first': 1, 'second': 2, 'third': 3}
    }
# pretty form
>>> axon.dumps(d, pretty=1)
{ age: 27
  name: "Joe"
  numbers: [1 2 3 4 5]
  subdict: {
    first: 1
    second: 2
    third: 3}}
# compact form
>>> axon.dumps(d)
{age:27 name:"Joe" numbers:[1 2 3 4 5] subdict:{first:1 second:2 third:3}}

It also can handle multiple objects in the message:

它还可以处理消息中的多个对象:

>>> msg = axon.dumps([{'a':1, 'b':2, 'c':3}, {'a':2, 'b':3, 'c':4}])
>>> print(msg)
{a:1 b:2 c:3} 
{a:2 b:3 c:4}
{a:3 b:4 c:5}

and then load them iteratively:

然后迭代加载它们:

for d in axon.iloads(msg):
   print(d)