Search code examples
yamlpython-3.5pyyaml

How to print a value with double quotes and spaces in YAML?


I am trying to dump a Python dictionary to YAML which has some strings as value fields.

import yaml
str1 = "hello"
str2 = "world"
mystr = "\"" + str1 + str(" ") + str2 + "\""
mydict = {"a" : mystr}
f = open("temp.yaml", "w")
yaml.dump(mydict, f, default_flow_style = False, \
                    explicit_start = "---", explicit_end = "...", encoding = 'UTF-8')
f.close()

the YAML I get is:

a: '"hello
 world"'

Notice, the value "hello world" is spilling to the next line. I am using python 3.5 and YAML module version is 3.11

Can someone tell me how to make the YAML look like below?

a: "hello world"

Solution

  • The code is a bit sloppy but it will give the results you want.

    global dict_keys
    
    def mk_double_quote(dumper, data):
        if data in dict_keys:
            return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='')
        else:
            return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"')
    
    yaml.add_representer(str, mk_double_quote)
    
    d = {'a': 'Hello World'}
    dict_keys = set(d.keys())
    
    f = open('temp.yaml', 'w')
    yaml.dump(d, f, default_flow_style=False, encoding='utf-8')
    f.close()
    

    The result will look like: a: "Hello World"