Acid Ascorbic
Acid Ascorbic

Reputation: 43

How can I load 'null' from .yml as None (class str), not (class NoneType)?

I have yaml that looks like this:

  SomeRecord:
    type: array
    items:
      type:
        - string
        - number
        - null

I try PyYAML and ruamel.yaml they both convert 'null' to None (class NoneType). Is there an easy way to change this behavior?

Upvotes: 1

Views: 7937

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49812

You can use a simple recursive function to find the None values and convert them to 'None' like this:

Code:

def convert_none_to_str(data):
    if isinstance(data, list):
        data[:] = [convert_none_to_str(i) for i in data]
    elif isinstance(data, dict):
        for k, v in data.items():
            data[k] = convert_none_to_str(v)
    return 'None' if data is None else data

Test Code:

yaml_data = """    
  SomeRecord:
    type: array
    items:
      type:
        - string
        - number
        - null
"""

import yaml
data = yaml.safe_load(yaml_data)
print(data)
convert_none_to_str(data)
print(data)

Results:

{'SomeRecord': {'type': 'array', 'items': {'type': ['string', 'number', None]}}}
{'SomeRecord': {'type': 'array', 'items': {'type': ['string', 'number', 'None']}}}

Upvotes: 3

Related Questions