Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

python - how to keep null value in yaml file while dumping though ruamel.yaml

I have YAML file site.yaml:

Kvm_BLOCK:
  ip_address: 10.X.X.X
  property: null
  server_type: zone

loaded and then dumped with:

ruamel.yaml.dump(site_yaml, new_file, Dumper=ruamel.yaml.RoundTripDumper)

it becomes

Kvm_BLOCK:
      ip_address: 10.X.X.X
      property: 
      server_type: zone

how to retain this null value in property block

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The null value in YAML 1.2 (constructed as Python's None) can be represented as null, Null, NULL and ~, as specified here.

Additionally:

Nodes with empty content are interpreted as if they were plain scalars with an empty value. Such nodes are commonly resolved to a “null” value.

Therefore your null value is not gone, it is just represented differently by the default representation for null in ruamel.yaml when using RoundTripDump. If you load that output again, you once more get a None as value for the key property


If that is not to your liking you can change the output for all None/null values by doing:

import sys
import ruamel.yaml


yaml_str = """
Kvm_BLOCK:
  ip_address: 10.X.X.X
  property: null
  server_type: zone
"""


def my_represent_none(self, data):
    return self.represent_scalar(u'tag:yaml.org,2002:null', u'NULL')

yaml = ruamel.yaml.YAML()
yaml.representer.add_representer(type(None), my_represent_none)

data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)

which will dump:

Kvm_BLOCK:
  ip_address: 10.X.X.X
  property: NULL
  server_type: zone

You can get finer grained control by creating different classes in Python (NULL, Null, null, etc. ) and have different representers for each of them (much in the same way that the string subclasses in ruamel.yaml.scalarstring.py are used to represent a string in different ways (double quoted, single quoted, literal block style scalar). The problem is that you cannot subclass NoneType so this is not so easily done transparently as with the string scalars.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...