Avoiding quotes in yaml field value

Question:

I have a yaml file with content

ip:
  modules:
    shutdown-manager:
      version: 0.5
      package:
        repo: github
        path: ~/path
        manager: no

This is my program

import ruamel.yaml

yaml = ruamel.yaml.YAML()

with open('manifest.yml') as stream:
   documents = yaml.load(stream)
   en=(documents['ip']['modules']['shutdown-manager'])
   en.insert(1, 'enabled', 'false')
   print(en)


with open('manifest_new.yml', 'wb') as stream:
    yaml.dump(documents, stream)

This is the ouput i get

ip:
  modules:
    shutdown-manager:
      version: 0.5
      enabled: 'false'
      package:
        repo: github
        path: ~/path
        manager: no

In the content of new yaml you can see there is quotes coming in enabled: ‘false’.
I want to avoid that quotes and the output should look like

ip:
  modules:
    shutdown-manager:
      version: 0.5
      enabled: false
      package:
        repo: github
        path: ~/path
        manager: no

How this can be achieved?

Asked By: ganeshredcobra

||

Answers:

You are explicitly setting the value of the enabled key to the string false, so yaml.dump produces a YAML string. Set it to the Boolean value False instead to get a YAML boolean.

Answered By: chepner

If you don’t get what you expect using ruamel.yaml, it is a good practise to load what you expect, see if that dumps back to what you expect without change, and then inspect that was what loaded.

You’ll see that the expected YAML dumps back unchanged (especially not without quotes around false), and that documents['ip']['modules']['shutdown-manager']['enabled'] equals the boolean value False. So you should insert that instead of the string 'false'.

Also note that you load only one document with .load(), if you potentially have a multidocument stream, use .load_all(). And the recommended extension for YAML files has been .yaml since Sept. 2006.

Answered By: Anthon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.