Home > Mobile >  change format with yaml dump python
change format with yaml dump python

Time:10-29

I need to create a yaml with the following format

hints:
    - {
        content: "...",
        ...
      } 

alredy tried to do something like data['hints'] = {"content" : "a", "foo" : "bar"} giving:

hints:
- content: "a"
  foo: "bar"

also tried data['hints'] = "{\n" f"content:{...}," "\n" ... "\n}", giving:

hints:
- '{

  content: ...,

  foo:bar,

  }'

CodePudding user response:

You can change the style with a custom representer, like so:

import sys, yaml

class BraceDict(dict):
    pass


def represent_brace_dict(dumper, data):
    ret = dumper.represent_dict(data)
    ret.flow_style = True
    return ret
yaml.add_representer(BraceDict, represent_brace_dict)

yaml.dump({
    "hints": [
        BraceDict(content = "a", foo = "bar")
    ]
}, sys.stdout)

Output:

hints:
- {content: a, foo: bar}

If you want to force quotes on values, use the same technique for them.

You can't force multiline output though. In any case,

I use a library that expects to receive that format in the yml

that sounds very strange, as the YAML spec requires that both formats must be supported. If a library doesn't implement this, it technically doesn't use YAML and therefore you shouldn't use a YAML library to generate its input.

  • Related