我正在生成作为协议的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))
然后我得到了这个输出
%YAML 1.1
---
sample:
content: "{\n \"other\": \"...\",\n \"type\": \"customer-account\",\n \"\
id\": \"123\"\n}"
description: This example shows the structure of the message
现在对我来说看起来好多了
如果我能够从管道|
我想看的输出是这个
%YAML 1.1
---
sample:
content: |
{
"other": "...",
"type": "customer-account",
"id": "123"
}
description: This example shows the structure of the message
看看这是多么容易阅读...
那么如何在python代码中解决这个问题呢?
答案 0 :(得分:2)
你可以这样做:
import sys
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=(',', ': '))
yaml.scalarstring.walk_tree(myyamel)
yaml.round_trip_dump(myyamel, sys.stdout, default_style = None, default_flow_style=False, indent=2, block_seq_indent=2, line_break=0, explicit_start=True, version=(1,1))
给出:
%YAML 1.1
---
sample:
description: This example shows the structure of the message
content: |-
{
"id": "123",
"type": "customer-account",
"other": "..."
}
一些注意事项:
因为您正在使用普通字典,所以YAML的打印顺序是实现和密钥相关。如果您希望将订单固定到您的作业,请使用:
myyamel['sample'] = yaml.comments.CommentedMap()
print(yaml.round_trip_dump)
,指定要写入的流,效率更高。 walk_tree
将所有具有换行符的字符串转换为递归阻止样式模式。你也可以明确地做:
myyamel['sample']['content'] = yaml.scalarstring.PreservedScalarString(json.dumps( jsonsample, indent=4, separators=(',', ': ')))
在这种情况下,您无需致电walk_tree()
即使您仍在使用Python 2,您应该开始习惯使用print
函数而不是print
语句。因为它包含在每个Python文件的顶部:
from __future__ import print_function