我的 yaml 看起来像这样:
SomeRecord:
type: array
items:
type:
- string
- number
- null
我尝试了 PyYAML 和 ruamel.yaml,它们都将 'null'
转换为 None
(类 NoneType)。
有没有简单的方法来改变这种行为?
最佳答案
您可以使用简单的递归函数来查找 None
值并将其转换为 'None'
,如下所示:
代码:
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']}}}
关于python - 如何从 .yml 加载 'null' 作为 None (类 str),而不是(类 NoneType)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50658360/