python - 如何从 .yml 加载 'null' 作为 None (类 str),而不是(类 NoneType)?

标签 python python-3.x yaml

我的 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/

相关文章:

yaml - 在 YAML 条目开头转义 &(与号)?

Python/Django - 如何在导航到新 View 之前获取页面 URL

python - (PY)升级pip和安装json包不起作用

ruby/hash:Chef::Node::ImmutableMash 将 Chef 属性转换为 yaml 时包含在文件中

python pdfplumber : extract pdf with data split into 2 columns

python - django 中 migrate 和 syncdb 命令的区别?

bash - 如何将curl输出保存在gitlab变量中?

python - 从 pandas 的 JSON 列中提取属于特定键的值

python - PyTorch 中的层类型及其激活函数有何区别?

python-3.x - 控制 seaborn regplot 置信区间半透明度