Using ruamel.yaml I tried to get a YAML in a certain style, more specifically one where single-line strings start at same line as :
and multi-line strings using a folded scalar style (|
/|-
) and lines being limited to a certain amount of characters (word-wrapped).
My attempt so far heavily influenced by a similar function called walk_tree
in the sources:
#!/usr/bin/env python
import ruamel.yaml
from ruamel.yaml.scalarstring import ScalarString, PreservedScalarString
def walk_tree(base):
from ruamel.yaml.compat import string_types
if isinstance(base, dict):
for k in base:
v = base[k]
if isinstance(v, string_types):
v = v.replace('\r\n', '\n').replace('\r', '\n').strip()
base[k] = ScalarString(v) if '\n' in v else v
else:
walk_tree(v)
elif isinstance(base, list):
for idx, elem in enumerate(base):
if isinstance(elem, string_types) and '\n' in elem:
print(elem) # @Anthon: this print is in the original code as well
base[idx] = preserve_literal(elem)
else:
walk_tree(elem)
with open("input.yaml", "r") as fi:
inp = fi.read()
loader=ruamel.yaml.RoundTripLoader
data = ruamel.yaml.load(inp, loader)
walk_tree(data)
dumper = ruamel.yaml.RoundTripDumper
with open("output.yaml", "w") as fo:
ruamel.yaml.dump(data, fo, Dumper=dumper, allow_unicode=True)
But then I get an exception: ruamel.yaml.representer.RepresenterError: cannot represent an object: …
. I get no exception if I replace ScalarString
with PreservedScalarString
as is the case in the original walk_tree
code but then I get the literal blocks again which is not what I want.
So how can my code be fixed so that it will work?