'how to get ruamel yaml emit blank instead of null?

Using ruamel.yaml, the emitted yaml is created like so:

from ruamel.yaml import YAML

ydata = dict(
  apiVersion='compliance.openshift.io/v1alpha1',
  disableRules=None,
  extends='tbd',
  kind='TailoredProfile',
  metadata=dict(name='Best Practices NIST CONTROLS Profile'),
  setValues=dict(v1='tbd'),
  title='tbd',
)

yaml = YAML(typ='safe')
yaml.default_flow_style = False      
with open(output_filepath, 'w') as outfile:
    yaml.dump(ydata, outfile)

and looks like this:

apiVersion: compliance.openshift.io/v1alpha1
disableRules: null
extends: tbd
kind: TailoredProfile
metadata:
  name: Best Practices NIST CONTROLS Profile
setValues:
  v1: tbd
title: tbd

But I want null to be blank, like so:

disableRules: 

How can that be done?



Solution 1:[1]

You are using typ='safe', which dumps faster then the default, but does always dump None` as null. If you use the (default) roundtrip dumper, you'll get the empty null representation when possible:

import sys
import ruamel.yaml

data = dict(
  apiVersion='compliance.openshift.io/v1alpha1',
  disableRules=None,
  extends='tbd',
  kind='TailoredProfile',
  metadata=dict(name='Best Practices NIST CONTROLS Profile'),
  setValues=dict(v1='tbd'),
  title='tbd',
)

    
yaml = ruamel.yaml.YAML()
yaml.dump(data, sys.stdout)

which gives:

apiVersion: compliance.openshift.io/v1alpha1
disableRules:
extends: tbd
kind: TailoredProfile
metadata:
  name: Best Practices NIST CONTROLS Profile
setValues:
  v1: tbd
title: tbd

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anthon