Reputation: 43
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
Reputation: 49812
You can use a simple recursive function to find the None
values and convert them to 'None'
like this:
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
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)
{'SomeRecord': {'type': 'array', 'items': {'type': ['string', 'number', None]}}}
{'SomeRecord': {'type': 'array', 'items': {'type': ['string', 'number', 'None']}}}
Upvotes: 3