【问题标题】:Convert Python dictionary to yaml将 Python 字典转换为 yaml
【发布时间】:2019-03-16 16:21:25
【问题描述】:

我有一本字典,我正在使用 python 中的yaml 模块将字典转换为 yaml。但是 Yaml 没有正确转换。

output_data = {
    'resources': [{
        'type': 'compute.v1.instance',
        'name': 'vm-created-by-deployment-manager',
        'properties': {
            'disks': [{
                'deviceName': '$disks_deviceName$',
                'boot': '$disks_boot$',
                'initializeParams': {
                    'sourceImage': '$disks_initializeParams_sourceImage$'
                },
                'autoDelete': '$disks_autoDelete$',
                'type': '$disks_type$'
            }],
            'machineType': '$machineType$',
            'zone': '$zone$',
            'networkInterfaces': [{
                'network': '$networkInterfaces_network$'
            }]
        }
    }]
}

我试过了:

import yaml
f = open('meta.yaml', 'w+')
yaml.dump(output_data, f, allow_unicode=True)

我得到meta.yaml 文件如下:

resources:
- name: vm-created-by-deployment-manager
  properties:
    disks:
    - autoDelete: $disks_autoDelete$
      boot: $disks_boot$
      deviceName: $disks_deviceName$
      initializeParams: {sourceImage: $disks_initializeParams_sourceImage$}
      type: $disks_type$
    machineType: $machineType$
    networkInterfaces:
    - {network: $networkInterfaces_network$}
    zone: $zone$
  type: compute.v1.instance

在这里,{sourceImage: $disks_initializeParams_sourceImage$}{network: $networkInterfaces_network$} 变得越来越像 dictionary意思是内在的 字典内容未转换为 yaml

我也试过了,

output_data = eval(json.dumps(output_data)) 
ff = open('meta.yaml', 'w+')
yaml.dump(output_data, ff, allow_unicode=True)

但得到相同的yaml 文件内容。

如何在 Python 中将完整的字典转换为 yaml?

【问题讨论】:

  • yaml.dump(output_data, ff, allow_unicode=True, default_flow_style=False)
  • @floydya :谢谢 .. 它奏效了。请写一个答案。这样我就可以接受并支持您的回答。

标签: python dictionary yaml


【解决方案1】:

默认情况下,PyYAML 根据是否有嵌套集合来选择集合的样式。如果一个集合有嵌套集合,它将被分配块样式。否则就会有流式风格。

如果您希望集合始终以块样式序列化,请将 dump() 的参数 default_flow_style 设置为 False。例如,

> `print(yaml.dump(yaml.load(document), default_flow_style=False))`
>> Result: `a: 1 b:   c: 3   d: 4`

文档:https://pyyaml.org/wiki/PyYAMLDocumentation

【讨论】:

    猜你喜欢
    • 2012-12-16
    • 2021-07-17
    • 2020-11-12
    • 2013-02-19
    • 2016-10-16
    • 1970-01-01
    • 2017-07-21
    • 2016-02-16
    • 1970-01-01
    相关资源
    最近更新 更多