简体   繁体   中英

Prettify a yml dump in python

I have this example:

import yaml
from collections import OrderedDict
data = [OrderedDict({"one": u"Hello\u2122", "two":["something", u"something2", u"something3"]})]
print yaml.dump(data, default_flow_style=False, default_style='"', allow_unicode=True, encoding="utf-8")

This prints out:

- !!python/object/apply:collections.OrderedDict
  - - - "two"
      - - "something"
        - !!python/unicode "something2"
        - !!python/unicode "something3"
    - - "one"
      - "Hello\u2122"

I use OrderedDict because I want to preserve the key order when dumping into YML. However, I don't care about the order when reading the YML back into python.

How can I prettify the dump to be something like:

- two:
    - "something"
    - "something2"
    - "something3"
  one:
    - "Hello\xe2\x84\xa2"

And then read it back into python using yaml.load() ?

One option is to use representers to change the serialization of some objects. But this has to be done on a case-by-case basis and I don't know if it will scale well for your particular use case.

Preserving the order in your OrderedDict will get a little more tricky, since the represent_mapping will always sort the items if your map has an items attribute, but passing the items as a tuple should work.

import yaml
from yaml.representer import SafeRepresenter
from collections import OrderedDict

data = [OrderedDict({"one": u"Hello\u2122",
                     "two":["something", u"something2", u"something3"]})]

# Represent an OrderedDict preserving order
def _represent_dict_in_order(dumper, odict):
    return dumper.represent_mapping(u'tag:yaml.org,2002:map', odict.items())

# Use a safe dictionary representer for OrderectDict
yaml.add_representer(OrderedDict, _represent_dict_in_order)

# Use a safe string representer for unicode data
yaml.add_representer(unicode, SafeRepresenter.represent_unicode)

print yaml.dump(data, default_flow_style=False,
                default_style='"', allow_unicode=True, encoding="utf-8")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM