$ ls ~yifei/notes/

Python 中的序列化库

Posted on:

Last modified:

basic usage

pickle.dumps(obj)  # dumps a object to a bytes, not binary safe
pickle.loads(bytes)  # loads a object from a bytes.

tricks

pickling dict is stable

In [5]: pickle.dumps({"a": "b", "1": "2"})
Out[5]: b"\x80\x03}q\x00(X\x01\x00\x00\x001q\x01X\x01\x00\x00\x002q\x02X\x01\x00\x00\x00aq\x03X\x01\x00\x00\x00bq\x04u."

In [6]: pickle.dumps({"1": "2", "a": "b"})
Out[6]: b"\x80\x03}q\x00(X\x01\x00\x00\x001q\x01X\x01\x00\x00\x002q\x02X\x01\x00\x00\x00aq\x03X\x01\x00\x00\x00bq\x04u."

json

json.dumps(dict,
    sort_keys=True,  # keys will be in order
)

Install

pip install pyyaml

Basic Example

import yaml
result = yaml.load(yaml_string) # to python list or dict
string = yaml.dump(py_object)
# NOTE: unlike the json module, the method here is load/dump, not loads/dumps

Yaml

YAML uses three dashes (“---”) to separate documents within a stream. Three dots ( “...”) indicate the end of a document without starting a new one, for use in communication channels.

empty string in yaml is '' or "", if you have a blank entry, it will be converted to None you don't need to quote strings in yaml

for dumping, when dumping to a file, do this

with open('file.yml', 'w') as f:
    yaml.dump(data, f, default_flow_style=False, allow_unicode=True)

yaml 中还可以通过 &

Reference

  1. https://stackoverflow.com/questions/45805380/meaning-of-ampersand-in-docker-compose-yml-file
WeChat Qr Code

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.

友情链接: MySQL 教程站