yaml / pyyaml

Canonical source repository for PyYAML
MIT License
2.53k stars 514 forks source link

Weird dumping when a literal block scalar contains trailing space #411

Open lhotakj opened 4 years ago

lhotakj commented 4 years ago

Hi, this issue is related to issue #402.

import yaml
raw_yaml = """
---
- weird parsing:
    content_ok: |
      this is OK
      without space

    content_bad: |
      this is not ok
      as it has a trailing space 
"""
s = yaml.safe_load(raw_yaml)
print(yaml.safe_dump_all(s, sort_keys=False, default_flow_style=False))

Python 3.7 gives you the following output:

weird parsing:
  content_ok: 'this is OK

    without space

    '
  content_bad: "this is not ok\nas it has a trailing space \n"

Note that content_bad is formatted differently than content_ok just because of a traling space. This small issue caused me a lot of headaches ;) Would it be possible to make dump method working consistently? Thanks a lot

danielburn5 commented 2 years ago

This is a real pain. Glad I found this issue to help me understand what was going on :) Would be great to get it fixed up.

evandrocoan commented 1 year ago

From this question https://stackoverflow.com/questions/71836675/force-pyyaml-to-write-multiline-string-literals-regardless-of-string-content, I moved to import ruamel.yaml as yaml and it dumped all strings correctly as required by content_ok on the first post by using default_style='|'

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# python3 -m pip install ruamel.yaml
import ruamel.yaml as yaml

raw_yaml = """
---
- weird parsing:
    content_ok: |
      this is OK
      without space

    content_bad: |
      this is not ok
      as it has a trailing space
"""
s = yaml.safe_load(raw_yaml)
print(yaml.safe_dump_all(s, default_flow_style=False, default_style='|'))

Result:

"weird parsing":
  "content_bad": |
    this is not ok
    as it has a trailing space
  "content_ok": |
    this is OK
    without space

With print("%s" % repr(yaml.safe_dump_all(s, default_flow_style=False, default_style='|'))) : '"weird parsing":\n "content_bad": |\n this is not ok\n as it has a trailing space \n "content_ok": |\n this is OK\n without space\n'

Erim32 commented 10 months ago

Up

Rishang commented 7 months ago

+1