pyyaml icon indicating copy to clipboard operation
pyyaml copied to clipboard

Unable to dump blocks without having quotes on keys

Open ssbarnea opened this issue 5 years ago • 7 comments

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

ssbarnea avatar Dec 07 '18 14:12 ssbarnea

I have the same problem, Somebody to help us?

YamanduTellechea avatar Jan 02 '19 08:01 YamanduTellechea

Has someone found a solution?

remorses avatar Jan 20 '19 17:01 remorses

I ran into this problem too. Any help is highly appreciated.

uniqx avatar Apr 09 '19 09:04 uniqx

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.

ysaakpr avatar Jun 18 '19 18:06 ysaakpr

looks like the if the value has ":" in it, then the whole value has to be in quotes in order to work with quotes

ysaakpr avatar Aug 30 '19 08:08 ysaakpr

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...

SleepyBrett avatar Aug 14 '20 21:08 SleepyBrett

Use ruamel.yaml instead

it is better documented than pyyaml: https://pypi.org/project/ruamel.yaml/

Yop-La avatar Feb 28 '22 12:02 Yop-La