作者:气质未央若 | 来源:互联网 | 2022-12-02 15:06
我有一个字典,我正在使用yaml
python中的模块将字典转换为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?
1> 小智..:
默认情况下,PyYAML
根据是否具有嵌套集合来选择集合的样式。如果一个集合具有嵌套的集合,则将为其分配块样式。否则它将具有流样式。
如果您希望集合始终以块样式进行序列化,请将default_flow_style
dump()的参数设置为False
。例如,
> `print(yaml.dump(yaml.load(document), default_flow_style=False))`
>> Result: `a: 1 b: c: 3 d: 4`
说明文件:https : //pyyaml.org/wiki/PyYAMLDocumentation