【问题标题】:How to get consistent quotes during PyYAML dump()?如何在 PyYAML 转储()期间获得一致的报价?
【发布时间】:2021-11-28 06:56:19
【问题描述】:

我想使用 PyYAML(使用 yaml.dump())将字典转储到 yaml 文件中。字典看起来像这样:

{'releases':
 {'release1': {'name': 'release1, 'version': '1.0.0', 'sha1': 'sha1'},
 {'release2': {'name': 'release2', 'version': '20', 'sha1': 'sha1'},
 {'release3': {'name': 'release3', 'version': '3.0', 'sha1': 'sha1'},
 ...

这些版本号可以有任何格式。例如。 1.0、2.0.1、30、v4、...
在转储期间,PyYAML 将单引号添加到可以解释为 float 或 int 的值。这是有道理的,而且似乎是有意的。然而,这使得最终的 yaml 文件看起来非常不一致(无论如何它都是有效的):

releases:
  release1:
    name: release1
    sha1: sha1
    version: 1.0.0
  release2:
    name: release2
    sha1: sha1
    version: '20'
  release3:
    name: release3
    sha1: sha1
    version: '3.0'
...

有没有办法对所有版本号强制使用引号?
我尝试使用default_flow_style,但它不起作用或向我不想要的键和值添加引号。

【问题讨论】:

    标签: python python-3.x yaml pyyaml


    【解决方案1】:

    如果你想控制 PyYAML 如何序列化值,你需要一个自定义序列化器,例如

    class SingleQuoted(str):
      pass
    
    def represent_single_quoted(dumper, data):
      return dumper.represent_scalar(BaseResolver.DEFAULT_SCALAR_TAG,
          data, style="'")
    
    yaml.add_representer(SingleQuoted, represent_single_quoted)
    

    如果你有这个,你可以通过用SingleQuoted 包装任何值来强制序列化单引号,例如

    SingleQuoted('1.0.0')
    

    【讨论】:

      猜你喜欢
      • 2022-07-29
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      相关资源
      最近更新 更多