我正在生成一个用作协议的YAML,其中包含一些生成的JSON。在
import json
from ruamel import yaml
jsonsample = { "id": "123", "type": "customer-account", "other": "..." }
myyamel = {}
myyamel['sample'] = {}
myyamel['sample']['description'] = "This example shows the structure of the message"
myyamel['sample']['content'] = json.dumps( jsonsample, indent=4, separators=(',', ': '))
print yaml.round_trip_dump(myyamel, default_style = None, default_flow_style=False, indent=2, block_seq_indent=2, line_break=0, explicit_start=True, version=(1,1))
然后我得到这个输出
^{pr2}$对我来说,这看起来会更好
如果我能够使多行行以管道|
开始格式化
我想看到的输出是
%YAML 1.1
---
sample:
content: |
{
"other": "...",
"type": "customer-account",
"id": "123"
}
description: This example shows the structure of the message
看看这是多么容易阅读。。。在
那么如何用python代码解决这个问题呢?在
您可以:
它给出了:
^{pr2}$注意事项:
由于您使用的是普通dict,所以YAML的打印顺序取决于实现和键。如果要将顺序固定到分配中,请使用:
print(yaml.round_trip_dump)
如果打印返回值,请指定要写入的流,这样效率更高。在walk_tree
递归地将所有包含换行符的字符串转换为块样式模式。也可以显式执行以下操作:在这种情况下,您不需要调用
walk_tree()
即使您仍在使用python2,您也应该开始习惯使用
print
函数而不是print
语句。在每个Python文件的顶部包括:相关问题 更多 >
编程相关推荐