pyyaml
pyyaml copied to clipboard
Unable to dump blocks without having quotes on keys
I am trying to dump JSON data into YAML in a way that makes is very easy to read by humans (as this goes to some logs).
Some of the values contain multiline strigs (stderr/stdout) and there is a must to avoid wrapping them.
data = json.loads("""{"key":"foo\\nbar"}""")
output = yaml.safe_dump(data,
allow_unicode=True,
default_flow_style=False,
canonical=False,
default_style="|")
print(output)
output = yaml.safe_dump(data,
allow_unicode=True,
default_flow_style=False,
canonical=False,
default_style=None)
print(output)
First formatting:
"key": |-
foobar
Second option:
key: 'foo
bar'
It seem that with default_style="|"
I do get the desired wrapping of multiline values but I lose the simplicity of the unquoted lines.
How can I get something like below?
key: |
foo
bar
I have the same problem, Somebody to help us?
Has someone found a solution?
I ran into this problem too. Any help is highly appreciated.
Same problem, my situation is very bad, I added
def str_presenter(dumper, data):
try:
dlen = len(data.splitlines())
if (dlen > 1):
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
except TypeError as ex:
return dumper.represent_scalar('tag:yaml.org,2002:str', data)
return dumper.represent_scalar('tag:yaml.org,2002:str', data)
But still some strings its not printing in block quoted, but some are.
looks like the if the value has ":"
in it, then the whole value has to be in quotes in order to work with quotes
using the ysaakpr method above, I get consistent results mostly..
In one of the documents that 'failed' (i.e. made a quoted escaped string) I found a "™" character, once I removed that it passed. I would not be surprised to learn that support for unicode is out of spec...
Use ruamel.yaml instead
it is better documented than pyyaml: https://pypi.org/project/ruamel.yaml/