Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dumping multiline string gives incorrect result #246

Closed
rjekker opened this issue Jan 26, 2019 · 3 comments
Closed

Dumping multiline string gives incorrect result #246

rjekker opened this issue Jan 26, 2019 · 3 comments
Labels

Comments

@rjekker
Copy link

rjekker commented Jan 26, 2019

(This is related to issue #240). Dumping a multiline string adds newlines, so the dumped data is different from the actual data. Consider the following:

Input.yaml

---
- |
  Hi!
  Second Line
  Another Line

My program:

import yaml
with open("input.yaml") as db:
    data = yaml.load(db)
    print(yaml.dump(data, default_flow_style=False))

The output:

- 'Hi!

  Second Line

  Another Line

  '

This is clearly incorrect: this simple program changes my data even though I am simply reading and dumping it

@perlpunk
Copy link
Member

It's not a bug. Both strings are actually the same. Represented in doublequotes:
"Hi!\nSecond Line\nAnother Line\n"
In single quotes, several lines get folded, so newlines vanish. Only if you have empty lines in between, the newline does not get folded.

May I recommend my article about quoting strings?
http://blogs.perl.org/users/tinita/2018/03/strings-in-yaml---to-quote-or-not-to-quote.html

I agree that in this case it would be nicer to output with the same block scalar style |, but figuring out which string style to use when dumping is not trivial.

@schollii
Copy link

schollii commented May 4, 2020

How about capturing some metadata about string at load time, eg if there is "|" take note of it for when it gets dumped. On a new element, you should be able to add that metadata.

@perlpunk
Copy link
Member

perlpunk commented May 4, 2020

@schollii sure, that would be possible, and ruamel.yaml does it.
But PyYAML has other issues right now that are more urgent IMHO, like YAML 1.2 support

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants